0
0
JavascriptHow-ToBeginner · 3 min read

How to Generate Random Number in Range in JavaScript

Use Math.random() to generate a random decimal between 0 and 1, then scale and shift it to your desired range with Math.floor(Math.random() * (max - min + 1)) + min. This returns a random integer between min and max, inclusive.
📐

Syntax

The general syntax to generate a random integer between two values min and max (inclusive) is:

  • Math.random(): generates a decimal number from 0 (inclusive) up to but not including 1.
  • (max - min + 1): calculates the size of the range.
  • Math.floor(): rounds down to the nearest whole number.
  • + min: shifts the number to start from the minimum value.
javascript
Math.floor(Math.random() * (max - min + 1)) + min
💻

Example

This example generates a random integer between 1 and 10, then prints it to the console.

javascript
const min = 1;
const max = 10;
const randomNumber = Math.floor(Math.random() * (max - min + 1)) + min;
console.log(randomNumber);
Output
7
⚠️

Common Pitfalls

One common mistake is forgetting to add + min, which causes the random number to always start from 0 instead of your minimum value. Another is using Math.round() instead of Math.floor(), which can skew the distribution and produce numbers outside the desired range.

javascript
// Wrong: Missing + min, always starts at 0
const wrong1 = Math.floor(Math.random() * (max - min + 1));

// Wrong: Using Math.round can produce max+1
const wrong2 = Math.round(Math.random() * (max - min)) + min;

// Correct way
const correct = Math.floor(Math.random() * (max - min + 1)) + min;
📊

Quick Reference

StepDescription
Math.random()Generates a decimal between 0 and 1 (not including 1)
(max - min + 1)Calculates the size of the range including both ends
Math.random() * (max - min + 1)Scales the decimal to the range size
Math.floor(...)Rounds down to get an integer within range
+ minShifts the number to start at the minimum value

Key Takeaways

Use Math.floor(Math.random() * (max - min + 1)) + min to get a random integer in range.
Always add + min to shift the range from zero to your desired minimum.
Avoid Math.round() as it can produce numbers outside the range.
Math.random() alone returns a decimal between 0 and 1, so scaling is needed.
Test your code to ensure the random numbers include both min and max values.