This post will discuss how to generate a random number between the specified range in JavaScript.

1. Using Math.random() function

The Math.random() function returns a floating-point, pseudorandom number greater than or equal to 0 and less than 1, which you can then scale to your desired range.

The following code generates a random number between min and max.

Download  Run Code

 
This works as Math.random() generates a pseudorandom value between 0 (inclusive) and 1 (exclusive). When multiplied by (max - min) + 1, the lower bound remains 0, but the upper bound becomes (max - min, max - min + 1). Now, after calling Math.floor(), the range becomes [0, max – min] and on adding min, the range becomes [min, max].

2. Using Underscore/Lodash Library

Another alternative is to use the _.random method from underscore or lodash library. It generates a random integer between the specified lower and upper bounds, both inclusive.

Download

 
If only a single argument is specified, _.random will generate a number between 0 and that number, both inclusive.

Download

That’s all about generating a random number between specified ranges in JavaScript.