JavaScript Random Number Generation

JavaScript random number generation allows you to generate unpredictable-looking numbers for games, random selections, simulations, quizzes, and other interactive applications. For example, you can use random numbers to roll a dice, generate a random password component, select a random item from an array, or create a lottery-style number generator.

JavaScript provides the Math.random() method to generate random numbers. By combining it with other mathematical operations, you can generate random numbers within a specific range.

In this tutorial, you will learn how to generate random numbers in JavaScript, create integers within a range, select random array elements, and build practical examples.

What Is Random Number Generation in JavaScript?

Random number generation is the process of producing numbers that appear to follow a random sequence.

JavaScript uses the built-in Math.random() method to generate a pseudo-random number between 0 (inclusive) and 1 (exclusive).

This means the generated number can be 0, but it will always be less than 1.

Example of Math.random()

let number = Math.random();

console.log(number);

Possible output:

0.724183920145

Your output will usually be different each time you run the program.

The Math.random() method does not accept arguments. It generates a decimal number in the range from 0 up to, but not including, 1.

To learn more about JavaScript’s built-in mathematical functions, see the JavaScript Number Methods and Math Methods tutorial.

Generate Random Integers in JavaScript

Sometimes, you need a whole number instead of a decimal number. For example, a dice game requires an integer between 1 and 6.

You can use Math.floor() with Math.random() to generate a random integer.

Using Math.floor() with Math.random()

The Math.floor() method rounds a number down to the nearest integer.

let number = Math.floor(Math.random() * 10);

console.log(number);

Possible output:

7

This example generates an integer from 0 to 9.

Here is how the expression works:

  • Math.random() generates a decimal from 0 up to, but not including, 1.
  • Multiplying the result by 10 produces a value from 0 up to, but not including, 10.
  • Math.floor() rounds the result down to an integer.

If you want to understand rounding in more detail, explore the JavaScript Math Methods tutorial.

Generate a Random Number Between Two Values

You can generate a random integer between a minimum and maximum value using this formula:

Math.floor(Math.random() * (max - min + 1)) + min;

Here, min represents the smallest possible integer, and max represents the largest possible integer. Both limits are included.

Example: Generate a Random Number Between 1 and 100

let min = 1;
let max = 100;

let randomNumber = Math.floor(
    Math.random() * (max - min + 1)
) + min;

console.log(randomNumber);

Possible output:

47

The result can be any integer from 1 through 100, inclusive.

How the Formula Works

Consider this expression:

Math.floor(Math.random() * (max - min + 1)) + min;

Each part has a specific purpose:

ExpressionPurpose
Math.random()Generates a decimal from 0 up to, but not including, 1
max - min + 1Calculates the number of possible integer values
Math.random() * (max - min + 1)Scales the random decimal to the required range
Math.floor()Converts the scaled value into an integer
+ minShifts the result to start at the minimum value

This formula is useful for games, random quizzes, number guessing applications, and many other projects.

Generate a Random Number Between 1 and 10

If you need a random integer between 1 and 10, you can use a shorter expression.

let number = Math.floor(Math.random() * 10) + 1;

console.log(number);

Possible output:

4

The result will always be an integer between 1 and 10.

This works because multiplying Math.random() by 10 produces a value below 10. Applying Math.floor() gives an integer from 0 to 9, and adding 1 shifts the range to 1 through 10.

Generate a Random Dice Roll

Random number generation is commonly used to simulate dice rolls in games.

A standard six-sided dice has values from 1 to 6.

let dice = Math.floor(Math.random() * 6) + 1;

console.log("Dice result: " + dice);

Possible output:

Dice result: 5

Every time you execute this code, JavaScript generates a new result between 1 and 6.

You can use this logic when developing board games, including dice-based games built with JavaScript.

Generate Multiple Random Numbers

You can use a loop to generate multiple random numbers. JavaScript loops repeat a block of code, making them useful for this task.

Example: Generate Five Random Numbers

for (let i = 1; i <= 5; i++) {
    let number = Math.floor(Math.random() * 100) + 1;

    console.log(number);
}

Possible output:

23
81
7
46
92

Each iteration generates an integer between 1 and 100.

The output will change when you run the code again. The same number may also appear more than once because each generation is independent.

Learn more about repetition and control flow in the JavaScript Loops tutorial.

Generate a Random Array Element

You can use random number generation to select an element from an array.

First, calculate a random index based on the array’s length. Then use that index to access the selected element.

Example: Select a Random Fruit

let fruits = ["Apple", "Banana", "Mango", "Orange", "Grapes"];

let randomIndex = Math.floor(Math.random() * fruits.length);

let randomFruit = fruits[randomIndex];

console.log(randomFruit);

Possible output:

Mango

The fruits.length property returns the number of elements in the array. Multiplying Math.random() by that length and applying Math.floor() produces a valid index.

Because JavaScript array indexes start at 0, the formula works for arrays of different lengths.

For more information, read the JavaScript Arrays tutorial and the JavaScript Array Methods tutorial.

Handle an Empty Array

An empty array contains no elements, so you should check that it is not empty before selecting a random element.

function getRandomItem(items) {
    if (items.length === 0) {
        return undefined;
    }

    let randomIndex = Math.floor(Math.random() * items.length);

    return items[randomIndex];
}

console.log(getRandomItem(["Red", "Blue", "Green"]));
console.log(getRandomItem([]));

Possible output:

Blue
undefined

The first call returns a randomly selected color. The second returns undefined because the array is empty.

Create a Random Number Generator Function

If you need random integers repeatedly, you can create a reusable function that accepts a minimum and maximum value.

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

console.log(getRandomNumber(1, 10));
console.log(getRandomNumber(50, 100));
console.log(getRandomNumber(200, 500));

Possible output:

8
76
342

The output values are examples. Your results will vary.

The getRandomNumber() function accepts two arguments and returns a random integer within the inclusive range.

For this simple implementation, pass valid integer values where min is less than or equal to max. If you want to build a more robust utility, validate the arguments before generating the number.

You can learn more about reusable code in the JavaScript Functions tutorial.

Build a Random Number Guessing Example

You can combine random number generation, variables, conditions, and user input to create a simple number guessing example.

The following code generates a secret number between 1 and 10 and compares it with a guess.

let secretNumber = Math.floor(Math.random() * 10) + 1;
let guess = 7;

if (guess === secretNumber) {
    console.log("Congratulations! You guessed correctly.");
} else {
    console.log("Wrong guess. The number was " + secretNumber);
}

Possible output:

Wrong guess. The number was 3

The output depends on the generated secret number. In this example, the guess is fixed at 7; a real guessing game could ask the user to enter a number and allow repeated attempts.

This example demonstrates how random values can make interactive applications more engaging.

Math.random() vs Math.floor()

These methods perform different tasks, but they are often used together.

MethodPurposeExample
Math.random()Generates a pseudo-random decimal from 0 up to, but not including, 1Math.random()
Math.floor()Rounds a number down to the nearest integerMath.floor(4.9) returns 4
Math.ceil()Rounds a number up to the nearest integerMath.ceil(4.1) returns 5
Math.round()Rounds to the nearest integerMath.round(4.6) returns 5

For random integers, Math.floor() is commonly used because it produces a predictable range when combined with Math.random().

Using Math.round() instead can produce uneven probabilities at the edges of a range. For a standard inclusive integer range, prefer the Math.floor() formula shown earlier.

Important Limitations of Math.random()

Although Math.random() is useful for everyday programming, there are some important limitations.

  • It generates pseudo-random numbers: The values are produced by an algorithm and are not guaranteed to be truly random.
  • The upper limit is exclusive: Math.random() never returns 1.
  • Repeated values are possible: Generating multiple numbers does not guarantee unique results.
  • It is not suitable for security-sensitive tasks: Do not use it for passwords, authentication tokens, session identifiers, or cryptographic keys.

For security-sensitive random values, use the browser’s crypto.getRandomValues() API or another appropriate cryptographically secure random generator.

Example: Generate a Cryptographically Secure Integer

The following browser example generates a cryptographically secure integer from 1 to 10, inclusive.

function getSecureRandomNumber(min, max) {
    if (
        !Number.isSafeInteger(min) ||
        !Number.isSafeInteger(max) ||
        min > max
    ) {
        throw new RangeError("Invalid integer range.");
    }

    const range = max - min + 1;
    const limit = Math.floor(4294967296 / range) * range;
    const values = new Uint32Array(1);

    let value;

    do {
        crypto.getRandomValues(values);
        value = values[0];
    } while (value >= limit);

    return min + (value % range);
}

console.log(getSecureRandomNumber(1, 10));

Possible output:

6

This example uses rejection sampling to avoid the uneven distribution that can occur when simply applying the remainder operator to a random integer. It assumes the requested range is small enough for the calculation to remain within safe integer limits.

Run this code in a browser environment that supports the Web Crypto API, typically in a secure context such as HTTPS or localhost. For applications involving sensitive information, use a well-reviewed security approach appropriate to your environment.

Common Mistakes in JavaScript Random Number Generation

Forgetting to Add the Minimum Value

This expression generates integers from 0 to 9, not from 1 to 10.

let number = Math.floor(Math.random() * 10);

To generate integers from 1 to 10, add 1.

let number = Math.floor(Math.random() * 10) + 1;

Forgetting the Plus One in an Inclusive Range

Consider this formula:

Math.floor(Math.random() * (max - min)) + min;

It does not include the maximum value. To include both endpoints, use max - min + 1.

Math.floor(Math.random() * (max - min + 1)) + min;

Expecting Unique Random Numbers

Random number generation can return the same value more than once. If your application requires unique values, you need additional logic, such as removing selected items from an array or shuffling an array of available values.

Using Math.random() for Password Security

Math.random() is not designed for cryptographic security. Use the Web Crypto API for security-sensitive random values instead.

Frequently Asked Questions

What is Math.random() in JavaScript?

Math.random() is a built-in JavaScript method that returns a pseudo-random decimal number greater than or equal to 0 and less than 1.

How do you generate a random integer in JavaScript?

Use Math.floor() with Math.random().

let number = Math.floor(Math.random() * 100) + 1;

console.log(number);

This generates an integer between 1 and 100, inclusive.

How do you generate a random number between two values?

Use the following formula when min and max are valid integers and both endpoints should be included.

Math.floor(Math.random() * (max - min + 1)) + min;

For example, Math.floor(Math.random() * 6) + 1 generates a number from 1 to 6.

Can Math.random() generate zero?

Yes. Math.random() can return 0, but it will not return 1.

Can Math.random() generate negative numbers?

Yes, you can use it to generate numbers within a negative range by supplying suitable minimum and maximum values to the random integer formula.

For example:

let number = Math.floor(Math.random() * 11) - 5;

console.log(number);

This generates an integer between -5 and 5, inclusive.

Does Math.random() generate unique numbers?

No. It can generate the same number multiple times. Additional logic is required when unique values are necessary.

Is Math.random() secure for passwords?

No. Use a cryptographically secure random generator, such as crypto.getRandomValues() in supported browser environments, for security-sensitive tasks.

What to Learn Next

Now that you understand random number generation, continue learning JavaScript concepts that help you build interactive applications: