0
0
JavascriptHow-ToBeginner · 3 min read

How to Use Math.random in JavaScript: Simple Guide

Use Math.random() in JavaScript to generate a random decimal number between 0 (inclusive) and 1 (exclusive). To get a random number in a different range, multiply or adjust the result accordingly.
📐

Syntax

Math.random() is a function that returns a random decimal number between 0 (inclusive) and 1 (exclusive). It takes no arguments.

  • Math: The built-in JavaScript object for math functions.
  • random(): The method that generates the random number.
javascript
Math.random()
Output
0.123456789 (example output, varies each run)
💻

Example

This example shows how to generate a random decimal between 0 and 1, then how to get a random integer between 1 and 10 by adjusting the output.

javascript
const randomDecimal = Math.random();
console.log('Random decimal between 0 and 1:', randomDecimal);

const randomInt1to10 = Math.floor(Math.random() * 10) + 1;
console.log('Random integer between 1 and 10:', randomInt1to10);
Output
Random decimal between 0 and 1: 0.726384 Random integer between 1 and 10: 7
⚠️

Common Pitfalls

Many beginners expect Math.random() to return integers or numbers in a specific range without adjustment. Remember, it always returns a decimal between 0 and 1.

Also, using Math.round() can cause uneven distribution of numbers. Instead, use Math.floor() to get a uniform integer range.

javascript
/* Wrong way: Using Math.round() can bias results */
const wrongRandomInt = Math.round(Math.random() * 10);

/* Right way: Use Math.floor() and add 1 for range 1-10 */
const rightRandomInt = Math.floor(Math.random() * 10) + 1;

console.log('Wrong:', wrongRandomInt);
console.log('Right:', rightRandomInt);
Output
Wrong: 0 Right: 7
📊

Quick Reference

UsageDescriptionExample
Math.random()Returns decimal between 0 (inclusive) and 1 (exclusive)0.534567
Math.floor(Math.random() * max)Random integer from 0 to max-1Math.floor(Math.random() * 5) // 0 to 4
Math.floor(Math.random() * (max - min + 1)) + minRandom integer between min and max inclusiveMath.floor(Math.random() * (10 - 1 + 1)) + 1 // 1 to 10

Key Takeaways

Math.random() returns a decimal between 0 (inclusive) and 1 (exclusive).
Multiply and adjust Math.random() output to get numbers in your desired range.
Use Math.floor() instead of Math.round() for uniform integer ranges.
Math.random() takes no arguments and is easy to use for simple random numbers.
Remember the output changes every time you run it, so results vary.