Open In App

What is the use of the Math.random Function in JavaScript ?

The Math.random() function in JavaScript is used to generate a pseudo-random floating-point number between 0 (inclusive) and 1 (exclusive).

Example 1: Here, Math.random() is used to generate a random number.






let randomNumber = Math.random();
// Outputs a random number between 0 and 1 (excluding 1)
console.log(randomNumber);

Output
0.7620477508766035

Example 2: Here, Math.random() generates a number between 0 and 1, * 10 scales it to a range between 0 and 10, Math.floor() rounds it down to the nearest integer, and + 1 shifts the range to be between 1 and 10.






let randomInteger = Math.floor(Math.random() * 10) + 1;
// Outputs a random integer between 1 and 10
console.log(randomInteger);

Output
10
Article Tags :