Generate a Random Number in Range With JavaScript/Node.js

JavaScript has built-in methods to generate a single, random number. You can leverage this feature to create your own method generating a random number in a range between two other numbers.

Node.js Series Overview

Random Integer Between X and Y (Exclusive Y)

Let’s say you want to generate an integer in a range between X and Y. For example, a number larger than 1024, but no bigger than 49151.

Create a new method called between which can be part of your app’s utilities. This between method accepts two arguments: min and max.

Calculate a random number between the min and max values like this:use Math.random() to generate a random number, multiply this random number with the difference of min and max and ultimately add min to it.

This random number is between min and max, but not an integer. Finally, round the number with Math.floor:

/**
 * Returns a random number between min (inclusive) and max (exclusive)
 */
function between(min, max) {  
  return Math.floor(
    Math.random() * (max - min) + min
  )
}

// Example:

console.log(  
  between(10, 200)
)
// 199 (this may vary for you :) )

The shortcoming of this approach: the max value can never be reached.

Random Integer Between X and Y (Inclusive Y)

Generating a random integer between X and Y, including Y, you must add a + 1 to the difference between max and min: (max - min + 1. Here’s the full code snippet for the between method:

/**
 * Returns a random number between min (inclusive) and max (inclusive)
 */
function between(min, max) {  
  return Math.floor(
    Math.random() * (max - min + 1) + min
  )
}

// Example:

console.log(  
  between(10, 200)
)
// 200 (this may vary for you :) )

This implementation generates a random integer that can also be the min or max value.

Explore the Library

Find interesting tutorials and solutions for your problems.