JavaScriptNumbers and Math
Math. random()
Returns a random number from 0 (inclusive) to 1 (exclusive).
- Returns
- A number in the range [0, 1).
Example
#JavaScript
const rollDice = () => Math.floor(Math.random() * 6) + 1
console.log(rollDice())
console.log(rollDice())
console.log(Math.random() < 1)Console
…
Every run gives different numbers. Click "Run again" to roll the dice once more.
Definition and usage
#The Math.random() function returns a pseudo-random floating-point number greater than or equal to 0 and less than 1. Every call gives a different value.
To get a random integer from a range, multiply the result by the number of possible values and round down: Math.floor(Math.random() * 6) + 1 is a dice roll from 1 to 6.
The results aren’t suitable for security-related uses, like passwords or tokens. For that, use crypto.getRandomValues() or crypto.randomUUID().
Syntax
#Syntax
Math.random()More examples
#JavaScript
const tips = ['Drink water', 'Take breaks', 'Code every day']
const randomTip = tips[Math.floor(Math.random() * tips.length)]
console.log(randomTip)Console
…
Browser support
#Widely available
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#- Formula for a random integer from min to max inclusive:
Math.floor(Math.random() * (max - min + 1)) + min. - For IDs and tokens use
crypto.randomUUID(), notMath.random().
Related entries
#Spotted a mistake or missing an example? Write to us.