JavaScript Recipes: Generate Random Numbers in a Range

Join the AI Workshop to learn more about AI and how it can be applied to web development. Next cohort February 1st, 2026

The AI-first Web Development BOOTCAMP cohort starts February 24th, 2026. 10 weeks of intensive training and hands-on projects.


Use a combination of Math.floor() and Math.random() to generate random integers.

This simple one line of code will return a number between 1 and 6 (both included):

Math.floor(Math.random() * 6 + 1)

There are 6 possible outcomes here: 1, 2, 3, 4, 5, 6.

General Formula

To generate a random integer between min and max (inclusive):

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

For example, to get a random number between 10 and 20:

Math.floor(Math.random() * (20 - 10 + 1) + 10)

Lessons in this unit:

0: Introduction
1: ▶︎ Generate Random Numbers in a Range
2: Get Index in for...of Loop
3: Unlimited Function Parameters
4: Return Result from Async Function
5: Encode and Decode URLs
6: Destructuring Tips
7: Number Formatting
8: Regex Recipes
9: Dynamic function name in JS