Generating Random Numbers using Javascript

Generating Random Numbers using Javascript

ยท

3 min read

Have you ever needed to get a random number?

Maybe you need it for a game.

Maybe you need it to pick a lucky winner.

Maybe you just need random randomness in your life.

Well in this article we will discuss how to generate a random number using Javascript.


Generate a Number Between Zero to Value minus One

To generate a Random Number Between 0 to a Value minus one we use the ff code:

Math.floor(Math.random() * <value>);

So for example you need to get a value from 0 to 9 you just replace 'value' with 10 .

Why did we put 10 instead of 9?

Remember: the code generates a Number between zero to value -1

//Generates a random number between 0 - 9
Math.floor(Math.random() * 10);

This is useful whenever you need to access a random value of an array since the last index of an array is always Array. length -1.


Generate a Number Between Zero to value

To generate a Random Number Between 0 to Value we just add 1 to the formula:

Math.floor(Math.random() * <value>+1);

Simple as that! ๐Ÿ˜†

//Generates a random number between 0 - 10
Math.floor(Math.random() * 10+1);

This is useful whenever you need to access a random value of an array since the last index of an array is always Array. length -1.


Generate a Number Between Values

Now, what if we don't want to start at Zero.

What if we need to start from 1 or 2?

For that, we need this Function

//Generates a random number between minRange to maxRange -1
Math.floor(Math.random() * (maxRange - minRange))+minRange;

huh

Yes, that is the formula you need to use. It may be confusing but it works.

So for example we need to get a number from 3 to 10 then we use the code below.

//Generates a random number between 3 - 10

Math.floor(Math.random() * (10-3+1))+3;

// We added +1 to include 10 to the generation.

We added +1 to the example above so that 10 would be included in the random number generated.

Without it, the range would be from 3 to 9.


#Conclusion

And that's it!

That's how you generate random numbers using Javascript.

Here is a bonus pointer though.

Remember Javascript has a loose definition of datatypes. Meaning it does not know if what you inputted is a number or a string.

So my suggestion is if you are using a formula to pass the values of minRange and maxRange use parseInt to explicitly convert them to Integer.

//snippet of parsing min and max
 let minRange = parseInt(this.state.min);
 let maxRange = parseInt(this.state.max);

Trust me on this

It took me a few minutes to realize why I was getting a value greater than my max range.


#Thank You Corner

Thank you for reading this article and always supporting me!

If you want to reach out or maybe just say hi, you can contact me via Twitter

ย