Ad space (banner)
🟨JavaScript Lessons
Lesson 54 / 69

Generating Random Numbers

In this lesson you'll learn how to generate random numbers using Math.random(), so you can build programs with random elements like dice or drawing lots. This is for people searching "JavaScript how to generate random numbers" or "Math.random usage."

Math.random() returns a random decimal number greater than or equal to 0 and less than 1. By converting it into an integer range, or picking a random element from an array, you can build programs like dice or drawing lots — the result changes every time you run it. The combination Math.floor(Math.random() * range) + start is the classic way to produce a random integer within a specified range.

The sample code produces a die roll from 1 to 6 with Math.floor(Math.random() * 6) + 1, and picks a Rock-Paper-Scissors move by combining an array with a random index. Try reloading and running it several times to confirm the result changes each time.

A common beginner stumbling block is the range formula. If you want a random number "from 1 to 6," using just Math.floor(Math.random() * 6) alone gives a range of 0 to 5. Don't forget to add the starting value (1, in this case) at the end. Since the result changes on every run, try running it repeatedly to check the behavior yourself.

This is an indispensable basic function whenever you want to bring unpredictable elements into a program — a game's hit detection, a shuffle feature, generating part of a password, and more. It's also worth knowing that scenarios requiring strict security (like generating a fully secure password) need a more secure, dedicated API.

JavaScript
OUTPUT

💡 Anything passed to console.log() appears in the output below.

Ad space (banner)
Ad space (in-article)