The Math.random() method in JavaScript is used to generate random numbers. It is commonly used in games, simulations, OTP generation, shuffling data, and creating random IDs. This guide explains how Math.random() works and how to use it to generate random values in different ranges with simple examples.

What Is Math.random() in JavaScript?

Math.random() returns a random decimal number between 0 (inclusive) and 1 (exclusive).

Syntax:

Example:

Explanation:

Generates a random number like 0.2456, 0.8765, etc. The value is always greater than or equal to 0 and less than 1.

Generate Random Decimal Number in a Range

To generate a random decimal number between two values:

Explanation:

  • Math.random() gives a value between 0 and 1

  • Multiplying by (max - min) scales the range

  • Adding min shifts the result into the required range

Generate Random Integer Between Two Numbers

To generate a random integer between two numbers (inclusive):

Explanation:

  • Math.random() generates a decimal

  • Multiplying by (max - min + 1) sets the range

  • Math.floor() converts it into an integer

  • Adding min ensures the value starts from the minimum

Generate Random Integer Between 0 and N

Explanation:

Generates a random integer between 0 and n (inclusive).

Generate Random Boolean Value

Explanation:

Returns true or false randomly.

Pick a Random Element from an Array

Explanation:

  • items.length gives total elements

  • A random index is generated

  • The element at that index is selected

Generate Random OTP (4-Digit Number)

Explanation:

Generates a random 4-digit number between 1000 and 9999.

Shuffle an Array Using Math.random()

Explanation:

Randomly changes the order of elements in the array.

Common Mistakes with Math.random()

  • Assuming Math.random() returns integers

  • Forgetting to use Math.floor() when integers are needed

  • Not adjusting the range properly

  • Expecting cryptographically secure randomness

Summary of Math.random() Usage

RequirementFormula
Random decimal (0 to 1)Math.random()
Random decimal (min to max)Math.random() * (max - min) + min
Random integer (min to max)Math.floor(Math.random() * (max - min + 1)) + min
Random integer (0 to n)Math.floor(Math.random() * (n + 1))
Random array itemitems[Math.floor(Math.random() * items.length)]

Conclusion

Math.random() is a simple and powerful method to generate random values in JavaScript. By combining it with Math.floor() and basic math, random numbers can be generated for different ranges and use cases like games, OTPs, and data shuffling.