Horje
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.

Javascript

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.

Javascript

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

Output

10



Reffered: https://www.geeksforgeeks.org


JavaScript

Related
How to Check if a Variable is of Type Number in JavaScript ? How to Check if a Variable is of Type Number in JavaScript ?
How to Create a Single Line Comment in JavaScript ? How to Create a Single Line Comment in JavaScript ?
How to Create a Multi Line Comment in JavaScript ? How to Create a Multi Line Comment in JavaScript ?
How to Exit a Loop Before it Completes all Iterations in JavaScript ? How to Exit a Loop Before it Completes all Iterations in JavaScript ?
How to use the ! Operator to negate a Boolean Value in JavaScript ? How to use the ! Operator to negate a Boolean Value in JavaScript ?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
13