Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to generate a random number

Short answer

Math.random() returns a number from 0 to 1. To get an integer in a range, multiply it and round down:

function randomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}
 
console.log(randomInt(1, 100));

A random array element

A random index is produced the same way:

const colors = ['red', 'green', 'blue'];
 
console.log(colors[Math.floor(Math.random() * colors.length)]);

A decimal number

For a decimal number in a range, multiply without rounding:

const randomFloat = (min, max) => Math.random() * (max - min) + min;
const value = randomFloat(1.5, 2.5);
 
console.log(value >= 1.5 && value < 2.5);

Output:

true

Common mistake

Math.round() instead of Math.floor() makes the edge values half as likely as the others. And for codes and passwords use crypto.getRandomValues(), not Math.random():

const counts = { 1: 0, 2: 0, 3: 0 };
for (let i = 0; i < 30000; i++) counts[Math.round(Math.random() * 2) + 1]++;
 
console.log(counts[2] > counts[1] * 1.5 ? 'the middle value comes out twice as often' : 'even');

Output:

the middle value comes out twice as often

Functions used in this recipe

  • Math.random — Returns a random number between 0 and 1.
  • Math.floor — Rounds a number down to an integer.

Thanks for reading!

Donate to the site — we work hard for you.