efoexg
Last Updated: August 20, 2017
·
4.738K
· afshinm
Add92525ab635b5119671269d24c1449

Shortest code for random number between 1 and N in JavaScript

Here I want to show you a tip for creating a random number between 1 and N in easiest and shortest way.

Code

Here is the code:

~~(Math.random() * N) + 1

All you need to do is to replace N with your upper number.

How?

In JavaScript we have Math.random() which creates a random number between 0 and 1, e.g. 0.3577353348955512. We use this function to have a random number, then we multiply that to our upper number (e.g. 6):

0.3577353348955512 * 6 = 2.1464120093733072

And then we get the floor number with double ~ operator (see this tip: https://coderwall.com/p/9b6ksa).

Say Thanks
Respond

6 Responses
Add your response

10477

And for the same with -ve random numbers: ~(Math.random() * N)

over 1 year ago ·
10479
Author

+1 for the ~~ operator, I didn't actually know that you can floor numbers like that, thanks for sharing

over 1 year ago ·
10486
0 nfyu8txkcy7l9htqq8v08golvgypn tq96e18gxteze wf5n43u8aci7u1puckp4vxyt753o6cjr

Please, forgive my dumb question. What is the point of the +1?

If Math.random()returns a random number between 0 and 1, in case of 1:

1 * 6 + 1

This returns 7.

over 1 year ago ·
10489

Math.random() return a random number between 0 (inclusive) and 1 (exclusive).

over 1 year ago ·
10492
0 nfyu8txkcy7l9htqq8v08golvgypn tq96e18gxteze wf5n43u8aci7u1puckp4vxyt753o6cjr

Thanks, @as32!

over 1 year ago ·
10729
F2af3ff36c10d206b74f68aacf68e08d

Math.floor is faster in new version of v8 ;)

over 1 year ago ·