Kirupa.com - Random Numbers in JavaScript

Have questions? Discuss this HTML5 / JavaScript tutorial with others on the forums.

In programming, it is often nice to be able to work with numbers whose values are a bit unpredictable. To create numbers that occur with (almost) no set pattern, one would need to use a function that returns a random value.

Before I go further, here is a simple example where you will see a random number when you click on the button:

[ click on the button to see a random number between 0 and 100 ]

Generating a random number is pretty straightforward because a function for doing this already exists, and this function is:

Math.random();

In JavaScript, Math.random() returns a number greater than or equal to 0 but less than 1. Another way of stating that is (0 <= n < 1) where n is the number you are looking for.

To configure a number to randomly fall within a range of numbers, use the following format:

Math.floor(Math.random()*(1+High-Low))+Low;

High refers to the largest number in your range, and Low refers to the lowest number in your range. For example, to get a number between 10 and 50, my line of code would look as follows:

Math.floor(Math.random() * 41) + 10;

A random number between 10 and 50 will be displayed. Scott goes into more detail in his blog post True Random Integers in Flash CS3, but I'll summarize this briefly.

Note - JavaScript and ActionScript are Similar

Yes, even though Scott's blog post uses ActionScript, the big-picture information applies to JavaScript as well. If you are still skeptical, see the Flash version of this tutorial!

Walking Through the Approach

You may be wondering why getting the a random number between a range of numbers is so...inelegant. The addition of the 1 seems almost silly in the grand scheme of things.

The reason is that Math.random() returns a number greater than or equal to zero AND less than 1. The function will never return a 1 as its value. It will return something like .9999999, but it won't be a 1. Because we are rounding the output by Math.floor where we round down to the nearest integer, if we did not add the 1, you will never get the maximum possible answer for High - Low when it is multiplied by Math.random().

Let's say we ignore the one. Your code would now look as follows:

Math.floor(Math.random() * 40) + 10;

Math.random() * 40 will never return a 40 because that would require Math.random() to return a 1. We know from the AS3 documentation that Math.random() will get close to 1, but it will never reach one. Let's be optimistic and say that Math.random() returns a .9999, and we multiply that value by 40. The answer you will receive will be 39.996.

Guess what Math.floor of 39.996 is going to be? It is going to be 39! When this 39 gets added to 10, you get a value of 49. As you can see, you have no conceivable way of getting an answer of 50 which is the high number in your range of values. The only solution is to add a 1 to the operation where you are subtracting High from Low. Once you do that, you will be able to generate all numbers within the range of your high and low numbers with equal frequency.

Conclusion

Well, this wraps up my explanation of how random numbers can be generated in Flash. If you would like to see what my example looks like, download the source file from below:

Getting Help

If you have questions, need some assistance on this topic, or just want to chat - post in the comments below or drop by our friendly forums (where you have a lot more formatting options) and post your question. There are a lot of knowledgeable and witty people who would be happy to help you out

Share

Did you enjoy reading this and found it useful? If so, please share it with your friends:

If you didn't like it, I always like to hear how I can do better next time. Please feel free to contact me directly at kirupa[at]kirupa.com.

Cheers!

Click on Start or Continue Discussion to add your message.

Read-only Archive of Old comments

Please enable JavaScript to view the comments powered by Disqus. blog comments powered by

Creating high-quality content is a team effort that takes a boatload of time. If you found what you see here helpful, please consider sending a small tip:

While tipping is entirely optional, we'll be your bestest friend forever if you do.

More Details & Options


This is a companion discussion topic for the original entry at http://www.kirupa.com/html5/random_numbers_js.htm

Hello
Thanks for the explanation
But i have question
Let’s say i want random number between 50 and 100
so i use this code
z=Math.random() * 50+ (100 -50)
console.log(z)
It works but what i don’t get is (100-50) is equal to 50 and outside the bracket 50 is added. Then how it returns between 50 and 100?

At the lowest end, Math.random() returns 0. When it does that, you have 0 * 50 + 50 which is 50.

At the highest end, Math.random() returns something really close to 1 like .9999. When you multiply that out, you get .9999 * 50 + 50 which is really close to 100.

Does this help? :grinning:

Thanks for explanation. I am the new web developer now still learning html css and javascript.

1 Like

Thanks for explanation @kirupa

1 Like