Generate Random Number in a Specified Range in JavaScript

This tutorial introduces how to generate random numbers inside a specified range in JavaScript. We will use the `Math.random()` function to generate random numbers and then shift them to a number inside the specified range.

`Math.random()` Function

This function returns a floating-point, pseudo-random number in the range `0` (inclusive) to `1` (exclusive) with an approximately uniform distribution over that range. But it doesn’t return cryptographically secure numbers.

{{ % step %}}

{{ % /step %}}

Example Code

``````
function getRandomIntInclusive(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1) + min);
}

getRandomIntInclusive(2,5);
``````

Output:

``````4
``````

Related Article - JavaScript Math

• Convert Radians to Degrees in JavaScript
• BigDecimal in JavaScript
• Add Two Numbers in JavaScript
• JavaScript Scientific Notation
• Calculate the Percentage in JavaScript
• Round a Number to the Nearest 10 in JavaScript
• Related Article - JavaScript Number

• Convert a Number to Binary Format in JavaScript
• Format a Number in JavaScript
• JavaScript Phone Number Format
• Check if Number Is Between Two Values in JavaScript
• The Effect of JavaScript Plus Equal
• Use a Seed to Generate Random Numbers in JavaScript