Random Numbers

Generate random numbers with Math.random().

SyntaxMath.floor(Math.random() * max) + min

Math.random() returns a random decimal between 0 (inclusive) and 1 (exclusive).

A random whole number

Multiply, then round down with Math.floor(). To get an integer from 1 to n:

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

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Generate a random integer to pick a daily deal product from an array of featured items.
  • Produce a random token suffix when creating temporary file names to avoid collisions.
  • Shuffle quiz questions into a random order each time a student starts a new attempt.

More examples

Random float between 0 and 1

Math.random() returns a pseudo-random float in the range [0, 1).

Example · js
const roll = Math.random();
console.log(roll); // e.g. 0.7341523...

Random integer in a range

Wraps Math.random() with Math.floor to produce a random integer between min and max inclusive.

Example · js
function randInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}
console.log(randInt(1, 6)); // simulates a die roll

Shuffle an array with random

Uses sort with a random comparator to shuffle an array – a simple technique for small arrays.

Example · js
const questions = ["Q1", "Q2", "Q3", "Q4"];
questions.sort(() => Math.random() - 0.5);
console.log(questions); // random order each time

Discussion

  • Be the first to comment on this lesson.
Random Numbers — JavaScript | SoundsCode