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).
Written by Afshin Mehrabani
Related protips
6 Responses
And for the same with -ve random numbers: ~(Math.random() * N)
+1 for the ~~ operator, I didn't actually know that you can floor numbers like that, thanks for sharing
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.
Math.random() return a random number between 0 (inclusive) and 1 (exclusive).
Thanks, @as32!
Math.floor is faster in new version of v8 ;)
Have a fresh tip? Share with Coderwall community!
JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.
Security insights from Cside