Math.random()

ES1+

Returns a floating-point, pseudo-random number in the range 0 to less than 1.

Syntax

Math.random()

Return Value

number

A random number between 0 (inclusive) and 1 (exclusive)

Examples

JavaScript
console.log(Math.random());
// 1부터 10 사이의 정수
console.log(Math.floor(Math.random() * 10) + 1);
Output:
// 0.7234567890123456 7

📌 When to Use

Use Math.random() for games, randomized UI elements, shuffling arrays, or generating non-security-critical random values.

⚠️ Common Mistakes

Using Math.random() for security-sensitive operations like generating tokens or passwords.

Off-by-one errors when generating random integers in a range.

Expecting Math.random() to return exactly 1 (it never does, the range is [0, 1)).

✅ Best Practices

For security-critical randomness, use crypto.getRandomValues() or the Web Crypto API instead.

Create helper functions for common patterns: randomInt(min, max), randomElement(array), shuffle(array).

⚡ Performance Notes

Math.random() is fast but not cryptographically secure. For high-performance applications needing many random numbers, consider using a seeded PRNG library.

🌍 Real World Example

Array Shuffle (Fisher-Yates)

Implement the Fisher-Yates shuffle algorithm to randomly reorder array elements.

function shuffleArray(array) {
  const shuffled = [...array];
  for (let i = shuffled.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
  }
  return shuffled;
}

const deck = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K'];
console.log(shuffleArray(deck));
// ['7', 'K', '3', 'A', '9', '5', '2', 'Q', '10', '4', '8', 'J', '6']

Related Methods