How to Generate a Random Number in JavaScript?
To generate a random number in JavaScript, use the built-in methods that produce a floating-point number between 0 (inclusive) and 1 (exclusive).
Below are the approaches to generate random numbers in JavaScript:
Table of Content
Using Math.random() method
The Math.random()method in JavaScript is a foundational function for generating pseudo-random floating-point numbers between 0 (inclusive) and 1 (exclusive).
Example: Randomly generating floating point number between 0 and 1 using the Math.random() method.
function random()
{
let randomNumber= Math.random();
console.log(randomNumber)
}
random();
function random()
{
let randomNumber= Math.random();
console.log(randomNumber)
}
random();
Output
0.576247647158219
Using Math.floor() with Math.random()
UsingMath.floor()with Math.random() in JavaScript enables the creation of random integers within a defined range. This combination ensures a predictable outcome for applications such as games and simulations."
Example: Randomly generating integer within a specific range using the Math.floor() method along with the Math.random() method.
function random() {
let randomNo = Math.floor(Math.random() * 10);
console.log(randomNo);
}
random();
function random() {
let randomNo = Math.floor(Math.random() * 10);
console.log(randomNo);
}
random();
Output
3
Using Math.ceil() with Math.random()
The Math.ceil()method in JavaScript is used to round a number up to the nearest integer greater than or equal to the original value.
Example: Generating random integer using Math.ceil() along with math.random() method.
const randomInteger = Math.ceil(Math.random() * 10);
console.log(randomInteger);
const randomInteger = Math.ceil(Math.random() * 10);
console.log(randomInteger);
Output
10
Using Math.round() with Math.random()
Using Math.round() with Math.random() in JavaScript allows for the generation of random integers by rounding the result of Math.random(). This is commonly used when a fair rounding to the nearest integer is needed.
Example: The below code uses Math.round() with Math.random() to generate random number.
const randomInteger =
Math.round(Math.random() * 10);
console.log(randomInteger);
const randomInteger =
Math.round(Math.random() * 10);
console.log(randomInteger);
Output
4