efoexg
Last Updated: August 20, 2017
·
5.39K
· afshinm

# Shortest code for random number between 1 and N in JavaScript

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

#### 6 Responses

10477

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

over 1 year ago ·
10479

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

over 1 year ago ·
10486

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

Thanks, @as32!

over 1 year ago ·
10729

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

over 1 year ago ·