Generate a Random Number with JavaScript

02/16/2022

Contents

In this article, you will learn how to generate a random number with JavaScript.

What is a random number?

A random number is a number that is not regular.
A typical example of a random number is a roll of dice.
If you roll the dice, there is no regularity and numbers from 1 to 6 appear randomly.
However, ordinary computers cannot generate true random numbers.
This is because the computer runs on a program that is a stack of reproducible calculations.
Therefore, when a random number is generated by a computer, it must be replaced with a value called “pseudo-random number” calculated based on some value.
That “some value” is called a seed.

How to generate a random number

Use the Math.random() function to generate a random number in JavaScript.
Math.random() will generate a floating point pseudo-random number in the range 0 or more and less than 1.

Below is sample code using the Math.random() method.

// Sample1
const val = Math.random();
console.log(val);


// Sample2
let array = [];
for (let i=0; i<10; i++) {
  array.push(Math.random());
}
console.log(array);


// Sample3
let array = [];
for (let i=0; i<10; i++) {
  array.push(Math.floor(Math.random() * 6) + 1);
}
console.log(array);