JavaScript Random Number Generator

Math.random() gives a decimal from 0 up to (not including) 1. These small functions turn it into what you usually need.

Random integer between min and max

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

console.log(randomInt(1, 6));    // like a dice
console.log(randomInt(10, 20));

The output is different each time. A sample run:

Tutorials Class - Output Window

4
17

Random item from an array

function randomItem(array) {
  return array[Math.floor(Math.random() * array.length)];
}

console.log(randomItem(["red", "green", "blue"]));

Shuffle an array (Fisher-Yates)

function shuffle(array) {
  const copy = [...array];
  for (let i = copy.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [copy[i], copy[j]] = [copy[j], copy[i]];
  }
  return copy;
}

console.log(shuffle([1, 2, 3, 4, 5]));
Note: Do not sort with array.sort(() => Math.random() - 0.5) to shuffle. It is biased. Also, Math.random() is not secure. For passwords and tokens use crypto.getRandomValues().

Related: Numbers and Math.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.