Course contentsShow
← JavaScript
Lesson 140 of 2,7234. Working with NumbersFree lesson

Generating Random Integers in a Range

Combining Math.random with Math.floor to create random integers within specific bounds.

Generating Random Integers in a Range

What you'll learn: How to combine Math.random() with Math.floor() to generate random whole numbers within a specific range.

The Core Problem

You already know Math.random() gives you a decimal between 0 (inclusive) and 1 (exclusive), like 0.7834. But what if you need a random integer between, say, 1 and 10? You need to scale that decimal to your desired range and then round it down to a whole number.

The Formula

To generate a random integer from min (inclusive) to max (inclusive):

Math.floor(Math.random() * (max - min + 1)) + min

Let's break this down step-by-step:

  1. max - min + 1 — Calculate how many possible integers exist in your range (including both endpoints)
  2. Math.random() * (max - min + 1) — Scale the random decimal to that range size
  3. Math.floor(...) — Round down to remove decimals, giving you a whole number
  4. + min — Shift the result to start at your minimum value

Example Walkthrough

To generate a random integer from 1 to 6 (like a dice roll):

let diceRoll = Math.floor(Math.random() * (6 - 1 + 1)) + 1;
// Math.random() * 6 gives 0 to 5.999...
// Math.floor() makes it 0, 1, 2, 3, 4, or 5
// + 1 shifts to 1, 2, 3, 4, 5, or 6

For a random number between 10 and 20:

let num = Math.floor(Math.random() * (20 - 10 + 1)) + 10;
// Possible results: 10, 11, 12... up to 20

Key Takeaway: Use Math.floor(Math.random() * (max - min + 1)) + min to generate random integers within any range—Math.random() provides randomness, multiplication scales it, Math.floor() makes it an integer, and adding min positions it correctly.