Generate a Random Number in JavaScript

This is a preview lesson
Register or sign in to take this lesson.

This tutorial shows how to generate a random number in JavaScript. In JavaScript, a random number is generated using Math.random() function and Math.floor() function.

Math.random() return value greater than 0 and less than 1.

Example 1 : Generate a Random Number

let a = Math.random();   
console.log(a); 

Output

0.6425032004727755

To find the random value between any two numbers:

Math.random() * (max- min) + min

Example 2 : Generate a Random Number between 1 and 100

const a = Math.random() * (10.-1) + 1
console.log(a);

Output

9.632445486515605

The examples generates the float random numbers. To generate the random numbers in integer, we use Math.floor() integer with Math.random() function.

Example 3 : Generate a Integer Random Number between 1 and 100

const a = Math.floor(Math.random() * (10.-1) + 1)
console.log(a);

Output

3