Enter Your Email Address to Watch This Lesson

Your link to unlock this lesson will be sent to this email address.

Unlock this lesson and all 1083 of the free egghead.io lessons, plus get TypeScript content delivered directly to your inbox!

Existing egghead members will not see this. Sign in.

Create random integers in a given range

1:53 TypeScript lesson by

Learn how to create random integers using JavaScript / TypeScript.

Get the Code Now
click to level up

egghead.io comment guidelines


Learn how to create random integers using JavaScript / TypeScript.

Javascript math.random function provides you with a random floating point number in the range 0 inclusive and 1 exclusive.

Let's go ahead and look for a hundred times, and look at the result for math at random. You can easily scale this 0 to less than 1 result to an upper limit by simple multiplication. For example, if you go ahead and multiply the result of 100, we get random values in the range 0 inclusive all the way up to less than 100.

You can limit this value to an integer if you wanted by simply using math.flow. Values in the range 0 to less than 1 get chopped to 0. The range 1 to less than 2 get chopped to 1, and so on till 99 to less than 100 gets chopped to 99.

A common challenge presented to beginning developers in an interview is to go ahead and create a function that should return an integer between a given start and end value. We start off by creating a function that accepts a start value and a before value.

We simply add start to the result that at least start is included. Next, we flow the value returned by math.random after scaling it up to the length of the start before range. As a demonstration, let's go ahead and run this function 100 times, and we can use a different start value if you wanted.

Joel's Head
Why are we asking?