Last Updated: May 29, 2023
·
8.013K
· afshinm

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).