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.
Javascript
let randomNumber = Math.random();
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.
Javascript
let randomInteger = Math.floor(Math.random() * 10) + 1;
console.log(randomInteger);
|
|