Generate a random number between specific range in JavaScript
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.
|
1 2 3 4 5 6 7 8 9 |
// Returns a random number between `min` and `max` (both inclusive) function random(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } var rand = random(2, 4); console.log(rand); // Expected Output: 2, 3, or 4 |
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.
|
1 2 3 4 5 6 7 8 9 10 11 |
var _ = require('underscore'); // Returns a random number between min and max function random(min, max) { return _.random(min, max); } var rand = random(2, 4); console.log(rand); // Expected Output: 2, 3, or 4 |
If only a single argument is specified, _.random will generate a number between 0 and that number, both inclusive.
|
1 2 3 4 5 6 7 |
var _ = require('underscore'); var n = 3; var rand = _.random(n); console.log(rand); // Expected Output: 0, 1, 2, or 4 |
That’s all about generating a random number between specified ranges in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)