JavaScript・Your syntax toolbox

Let's play with randomness

Fortunes, dice, loot boxes—the thrill of a result that changes every time you press comes from random numbers. Add "the fun of the unpredictable" to your page with Math.random.

A game’s loot box, a paper fortune, dice. Because the result changes every time you press, you want to try again and again—the thrill behind that is random numbers. With JavaScript, you can make one in a single line.

First, let’s see it in its raw form

console.log(Math.random());

A decimal like 0.8264097… shows up in the console. Run it again, and you get a completely different number. No one can tell what will come up.

Transforming it into a die

A decimal as-is is hard to use, so we process it into “a whole number from 1 to 6.” Here’s the standard formula.

const dice = Math.floor(Math.random() * 6) + 1;

Let’s read it from the inside out.

PartResult
Math.random()A decimal from 0 to 0.999…
× 6A decimal from 0 to 5.999…
Math.floor( )Rounds down the decimal part to a whole number from 0 to 5
+ 1Makes it 1 to 6

Math.floor is the tool for “rounding down” (floor = the floor of a room. Remember it as rounding toward the floor). Change the 6 part and you can make “1 to 10” or “1 to 100.” There’s a similar tool, Math.round, which rounds to the nearest, but it’s not suited to processing random numbers—with rounding to the nearest, only the numbers at both ends come up less often, so it won’t make a fair die. Remember to always go with rounding down.

A collection of handy recipes

Once you’ve learned the “multiply, round down, add” pattern, you can make all sorts of random numbers. Here are the forms you’ll use often.

The random number you wantHow to write it
A whole number from 0 to 9Math.floor(Math.random() * 10)
A whole number from 1 to 10Math.floor(Math.random() * 10) + 1
A whole number from 1 to 100Math.floor(Math.random() * 100) + 1
A one-in-two decisionMath.random() < 0.5

Only the last row has a different shape. The chance of Math.random()’s result being less than 0.5 is exactly half, so for a “50% decision” like a coin’s heads or tails, you can just write this expression directly as an if condition.

Splitting the path into three or more: else if

The if statement from last time was a two-way choice of “if / otherwise.” When you want to split into three or more, like a fortune, you slip an else if (“otherwise, if…”) in between.

if (num === 1) {
  console.log("Great luck!");
} else if (num === 2) {
  console.log("Good luck");
} else {
  console.log("So-so");
}

It checks from the top down, and only the first place that holds true runs.

JavaScriptIf it's..., then: the if statementWhen you want to review the basics of “if / otherwise,” this is the lesson

Let’s see it in action

With a combo of random numbers, else if, and events, your fortune is complete.

Every press draws a random number from 1 to 3, and ifelse ifelse picks which result to show. The same button, yet the result changes—this is the magic of random numbers.

Summary of this lesson

  1. Math.random() makes a random decimal that’s 0 or greater but less than 1
  2. “A whole number from 1 to 6” is Math.floor(Math.random() * 6) + 1—multiply, round down, add
  3. When splitting into three or more, slip an else if in between

Try it

The “random numbers” you learned this time won’t be used in Shima’s page. They’re a tool for pages that want to delight with a different result each time, like fortunes, quiz questions, or games. Keep them in mind, and use them when you need them.

FAQ

How do you make a random whole number from 1 to 10?
You write Math.floor(Math.random() * 10) + 1. The standard formula is: multiply by 'how many kinds you want (10),' round down, then add 'what number you start from (1).'
Can I use Math.round (rounding to the nearest) instead of Math.floor?
It's not recommended. With rounding to the nearest, only the smallest and largest numbers come up half as often as the others, so it won't be a fair die. For processing random numbers, rounding down (Math.floor) is the standard choice.
The same number came up twice in a row. Is it broken?
It's not broken. Just as a real die can roll the same face in a row, each draw is independent, so the same number coming up in a row is completely natural.