Generate Random Number in a Specified Range in JavaScript

  1. Math.random() Function
  2. Algorithm to Generate Random Number in a Specified Range in JavaScript
  3. Example Code

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.

Algorithm to Generate Random Number in a Specified Range in JavaScript

{{ % step %}}

  • ##### Generate a number between the range 0 and 1 and store it in a variable named rand.
  • ##### Calculate the total range range as max-min+1.
  • ##### Multiply range by rand and add it to min to get the random number inside the specified range.

{{ % /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
Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - JavaScript Math

  • Exponents in Javascript
  • Related Article - JavaScript Number

  • Square a Number in JavaScript