Darekdari / JavaScript Projects

Build a Dice Rolling Simulator in JavaScript

Learn how to simulate a dice roll with Math.random(), first in the console and then as an interactive web page. Try the live demo, then copy the source code and make it your own.

HTMLVanilla JavaScriptBeginner friendlyNo libraries
01 / Overview

How a Dice Rolling Simulator Works

A dice rolling simulator is one of the best first JavaScript projects: it is short, you can test it instantly, and it introduces functions, random numbers and the DOM. The whole idea fits in one line, because a roll is just a random whole number between 1 and the number of sides.

The formula

Math.random() returns a decimal from 0 up to (but never including) 1. Multiply it by 6 and you get a decimal from 0 up to just under 6. Math.floor() rounds that down to a whole number from 0 to 5, and adding 1 shifts the range to 1 to 6.

  • Math.random(): a decimal from 0 up to, but not including, 1.
  • * sides: stretches the range to 0 up to, but not including, the number of sides.
  • Math.floor(): rounds down to a whole number from 0 to sides – 1.
  • + 1: shifts the range to 1 to sides.
02 / Console

Step 1: Roll the Dice in the Console

Start with a plain function you can run in a browser console or in Node.js. The version below improves the basic idea in two ways: rollDie accepts any number of sides, and rollDice rolls several dice and returns both the individual rolls and the total.

dice.js
// Roll one die with any number of sides (default 6)
function rollDie(sides = 6) {
  return Math.floor(Math.random() * sides) + 1;
}

// Roll several dice and return the rolls and their total
function rollDice(count = 1, sides = 6) {
  const rolls = Array.from({ length: count }, () => rollDie(sides));
  const total = rolls.reduce((sum, n) => sum + n, 0);
  return { rolls, total };
}

// Call the function to roll two dice
const result = rollDice(2);
console.log('The dice rolled: ' + result.rolls.join(' + ') + ' = ' + result.total);

Run it several times and you will see a different result each time. Open your browser’s developer console, paste the code, and press Enter to see the output.

Good to know: Math.random() is fine for games and exercises, but it is not cryptographically secure. Do not use it for passwords, tokens or anything involving real money.
03 / Web page

Step 2: Build the HTML Dice Page

Now show the result on a page. The original version used an inline onclick attribute and a plain paragraph. This one attaches the click handler with addEventListener, lets visitors choose how many dice to roll, and announces the result to screen readers with aria-live. The layout is responsive, so it works on phones, tablets and desktops.

index.html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Dice Rolling Simulator</title>
  <style>
    body { font-family: Arial, sans-serif; text-align: center; padding: 16px; }
    #dice { display: flex; flex-wrap: wrap; gap: 12px; justify-content: center; margin: 20px 0; }
    .die {
      width: clamp(64px, 18vw, 100px);
      aspect-ratio: 1;
      display: grid;
      place-items: center;
      border: 3px solid #333;
      border-radius: 16px;
      font-size: 2rem;
      font-weight: bold;
    }
    button, select { padding: 12px 20px; font-size: 1rem; }
  </style>
</head>
<body>
  <h1>Dice Rolling Simulator</h1>

  <label>Dice
    <select id="count">
      <option>1</option><option>2</option><option>3</option>
    </select>
  </label>
  <button id="roll">Roll the Dice</button>

  <div id="dice"></div>
  <p id="result" aria-live="polite"></p>

  <script>
    function rollDie(sides = 6) {
      return Math.floor(Math.random() * sides) + 1;
    }

    document.getElementById('roll').addEventListener('click', () => {
      const count = Number(document.getElementById('count').value);
      const box = document.getElementById('dice');
      let total = 0;
      box.textContent = '';
      for (let i = 0; i < count; i++) {
        const n = rollDie();
        total += n;
        const die = document.createElement('div');
        die.className = 'die';
        die.textContent = n;
        box.appendChild(die);
      }
      document.getElementById('result').textContent = 'The dice rolled: ' + total;
    });
  </script>
</body>
</html>

How it works

The click handler reads how many dice to roll, calls rollDie() once for each, builds a tile for every result and adds the numbers into a total. Creating the tiles with createElement and textContent keeps the page safe and fast.

04 / Try it

Live Demo: Dice Rolling Simulator in Action

This demo goes one step further than the code above. Choose how many dice to roll and how many sides they have, then press the button. Six-sided dice show real pips, and the simulator keeps a short history and basic statistics.

Press the button to roll.
Tip: press Space or Enter while the button is focused
    Rolls0
    Average–
    Highest–
    05 / Level up

    Ideas to Extend the Simulator

    Once the basic roller works, these upgrades make good practice:

    • Custom dice: let the visitor type any number of sides, for tabletop games that use unusual dice.
    • Sound and animation: add a rolling sound and a CSS animation so the roll feels physical.
    • Game logic: build a two-player game where the highest total wins the round and a score is kept.
    • Roll statistics: count how often each number appears and draw a bar chart to see the distribution.
    • Saved history: store past rolls in localStorage so they survive a page refresh.
    • Keyboard shortcut: roll when the visitor presses the Space bar anywhere on the page.
    06 / Practice

    JavaScript Exercises Using the Dice Roller

    A dice roller is a great base for javascript exercises for beginners because every feature uses a core concept: variables store the rolls, functions do the work, and events connect the button to the page. If you want javascript exercises and solutions to compare against, try writing each challenge on your own before you look at the code above.

    Variables and functions

    Begin with javascript variables exercises, such as storing the number of sides in a variable and changing it to see how the results change. Then move on to javascript function exercises by writing a function that rolls two dice and reports whether they match.

    Challenges to try next

    These javascript practice exercises with solutions are easy to check because the live demo shows the expected behavior. Treat them as javascript tasks for practice, or as quick js exercises you can finish in one sitting:

    1. Roll a die until you get a six and count how many rolls it took.
    2. Roll two dice and detect doubles.
    3. Simulate 1,000 rolls and print how many times each number appeared.
    4. Add a “Roll again” streak counter that resets when the result changes.

    For more javascript exercises, browse our JavaScript projects.

    07 / FAQ

    Frequently Asked Questions

    How do you simulate a dice roll in JavaScript?

    Use Math.floor(Math.random() * 6) + 1. Math.random() gives a decimal below 1, multiplying by 6 stretches it, Math.floor() rounds down, and adding 1 turns the 0 to 5 range into 1 to 6.

    Why add 1 after Math.floor?

    Without it, the result would range from 0 to 5. Dice start at 1, so adding 1 shifts every possible result up by one.

    Is Math.random() truly random?

    It is pseudo-random: it produces numbers that look random and are fine for games. For security-sensitive tasks, use crypto.getRandomValues() instead.

    How can I roll dice with a different number of sides?

    Replace 6 with a variable. The rollDie(sides) function in this tutorial accepts any number of sides, such as 4, 8, 12 or 20.

    Is JavaScript hard for beginners?

    It has a gentle start because you see results immediately in the browser. Small projects like this one are a motivating way to learn functions, events and the DOM.

    Conclusion

    Keep Rolling with JavaScript

    You built a dice rolling simulator in three stages: a console function, a responsive web page, and an interactive demo with several dice, different sides and statistics. Along the way you learned how Math.random(), Math.floor() and a small offset turn a decimal into a fair roll, and how to show the result safely in the DOM.

    From here you can turn the roller into a full game, add sounds, or track statistics. Every feature you add reinforces the core JavaScript skills you will use in bigger projects.

    Learn more

    More info about us

    Scroll to Top