How to generate a random integer in JavaScript

Generating random integers is crucial for dice games, array indexing, ID generation, and implementing features like random selection, lottery systems, or procedural content creation in JavaScript applications. With over 25 years of experience in software development and as the creator of CoreUI, I’ve implemented random integer generation extensively in components like pagination randomizers, content selectors, and game mechanics where discrete whole numbers are required for proper functionality. From my extensive expertise, the most reliable approach is combining Math.random() with Math.floor() to convert floating-point numbers to integers within specific ranges. This method provides precise control over the range and ensures truly random distribution of whole numbers.

Use Math.floor() with Math.random() to generate random integers within a specified range.

const randomInt = Math.floor(Math.random() * 10)
// Result: 0, 1, 2, 3, 4, 5, 6, 7, 8, or 9

const randomBetween = Math.floor(Math.random() * (10 - 1 + 1)) + 1
// Result: 1, 2, 3, 4, 5, 6, 7, 8, 9, or 10

The Math.floor() function rounds down to the nearest integer, converting the decimal result from Math.random() to a whole number. In the first example, Math.floor(Math.random() * 10) generates integers from 0 to 9 (inclusive). For a range between two values, use the formula Math.floor(Math.random() * (max - min + 1)) + min. The second example generates integers from 1 to 10 inclusive. The + 1 ensures the maximum value is included in the possible results.

Best Practice Note:

This is the same approach we use in CoreUI components for generating random IDs, selecting random items from arrays, and implementing game mechanics across our component library. Create a reusable function: const randomInt = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min. For array index selection, use Math.floor(Math.random() * array.length). Always verify your range calculations to ensure both minimum and maximum values can be generated as expected.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author