Back to subject
JavaScript/Numbers & Math

Build a Simple Dice Roller

Practical lesson

Let's read a dice-roll expression and understand exactly how it produces a whole number from 1 to 6.

Math.random() first returns a raw decimal, somewhere from 0 up to (but never quite reaching) 1 something like 0.4837291.

Multiplying by 6 (Math.random() * 6) stretches that range to 0 up to (but never quite reaching) 6 so now the possible values span roughly 0.0 to 5.999...

Math.floor(...) then rounds that down to a whole number, giving you exactly 0, 1, 2, 3, 4, or 5 six possible whole-number outcomes, each equally likely.

Finally, + 1 shifts that range up by one, turning "0 through 5" into "1 through 6" a proper six-sided die. This exact pattern Math.floor(Math.random() * range) + start is worth memorizing; it's the standard way to get a random whole number within any range in JavaScript.

Try it yourself
Code

Starter example

Code
<script>
  const num = 4.7;
  const roll = Math.floor(Math.random() * 6) + 1;
  document.body.innerHTML = `
    <p>Rounded: ${Math.round(num)}</p>
    <p>Floor: ${Math.floor(num)}</p>
    <p>Ceil: ${Math.ceil(num)}</p>
    <p>Dice roll (1-6): ${roll}</p>
  `;
</script>
Live preview