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
JavaScript Variables
JavaScript Scope
JavaScript Data Types
JavaScript Type Conversion
JavaScript Operators
JavaScript Numbers and Math
Exercises & Assignments
Write a JavaScript program to add two numbers
Write a JavaScript program to swap two variables
Interview Questions & Answers
What are the data types in JavaScript?
What is the difference between == and === in JavaScript?
What is NaN in JavaScript?
What is the difference between null and undefined?
What is scope in JavaScript?
What is the difference between var, let and const?
What is hoisting in JavaScript?