MoreLesson 281Free preview
JS Random Number
This lesson is part of How To · All levels
Summary
Math.random() yields a random decimal number from 0 (inclusive) to less than 1. To get an integer in a certain range, multiply by the number of possible values and then round it down and add the minimum value. If a number is used for security like a token, use crypto.getRandomValues(), not Math.random().
Key points
- Math.random() always yields 0 <= x < 1 and never exactly 1.
- The integers 0 to n-1: Math.floor Math.random() * n).
- Inclusive range min to max: Math.floor(Math.random() * (max - min + 1)) + min.
- Math.random() is not suitable for security tokens or passwords.
Full lesson
Code examples and quizzes
Full lessons, code examples, and quizzes are available to subscribers. 5 questions.