How to generate random number in Javascript?

By FoxLearn 12/11/2024 2:07:54 AM   50
In JavaScript, you can generate random numbers using the Math.random() function. This function returns a random floating-point number between 0 and 1.

For example: Random floating-point number between 0 and 1

let randomNumber = Math.random();

To generate a random integer between a minimum (min) and maximum (max) value, you can scale and round the result.

For example: Random integer between a specified range

function getRandomInt(min, max) {
    min = Math.ceil(min); // round up the minimum value
    max = Math.floor(max); // round down the maximum value
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

let randomInt = getRandomInt(1, 10); // Random integer between 1 and 10

If you want a random decimal number within a given range, you can scale the result from Math.random() accordingly.

For example: Random floating-point number between a specified range

function getRandomFloat(min, max) {
    return Math.random() * (max - min) + min;
}

let randomFloat = getRandomFloat(1.5, 5.5); // Random decimal between 1.5 and 5.5

If you need a random boolean value, you can use Math.random() and check if it is less than 0.5.

For example: Random Boolean (true or false)

let randomBoolean = Math.random() < 0.5;