Often while developing projects, you will find yourself looking for ways to generate random numbers.

The most common use cases for generating random numbers are games of chance like rolling dice, shuffling playing cards, and spinning roulette wheels.

In this guide, you will learn how to generate a random number using the Math.random() method by building a mini dice game.

The Math.random() method

The Math object in JavaScript is a built-in object that has properties and methods for performing mathematical calculations.

A common use of the Math object is to create a random number using the random() method.

const randomValue = Math.random();

But the Math.random() method doesn't actually return a whole number. Instead, it returns a floating-point value between 0 (inclusive) and 1 (exclusive). Also, note that the value returned from Math.random() is pseudo-random in nature.

Random numbers generated by Math.random() might seem random, but those numbers will repeat and eventually display a non-random pattern over a period of time.

This is because algorithmic random number generation can never be truly random in nature. This is why we call them pseudo-random number generators (PRNGs).

To learn more about the Math.random() method you can check out this guide.

Random Number Generator Function

Now let's use the Math.random() method to create a function that will return a random integer between two values (inclusive).

const getRandomNumber = (min, max) => {
  return Math.floor(Math.random() * (max - min + 1)) + min;
};

Let's break down the logic here.

The Math.random() method will return a floating-point number between 0 and 1 (exclusive).

So the intervals would be as follows:

[0 .................................... 1)

[min .................................... max)

To factor the second interval, subtract min from both ends. So that would give you an interval between 0 and max-min.

[0 .................................... 1)

[0 .................................... max - min)

So now, to get a random value you would do the following:

const x = Math.random() * (max - min)

Here x is the random value.

Currently, max is excluded from the interval. To make it inclusive, add 1. Also, you need to add the min back that was subtracted earlier to get a value between [min, max).

const x = Math.random() * (max - min + 1) + min

Alright, so now the last step remaining is to make sure that x is always an integer.

const x = Math.floor(Math.random() * (max - min + 1)) + min

You could use the Math.round() method instead of floor(), but that would give you a non-uniform distribution. This means that both max and min will have half a chance to come out as an outcome. Using Math.floor() will give you perfectly even distribution.

So now that you have a fair understanding of how a random generation works, let's use this function to simulate rolling dice.

The Rolling Dice Game

In this section, we will create a really simple mini dice game. Two players enter their name and will roll the dice. The player whose dice has a higher number will win the round.

First, create a function rollDice that simulates the action for rolling the dice.

Inside the function body, call the getRandomNumber() function with 1 and 6 as the arguments. This will give you any random number between 1 and 6 (both inclusive) just like how real dice would work.

const rollDice = () => getRandomNumber(1, 6);

Next, create two input fields and a button as shown below:

<div id="app">
      <div>
        <input id="player1" placeholder="Enter Player 1 Name" />
      </div>
      <div>
        <input id="player2" placeholder="Enter Player 2 Name" />
      </div>
      <button id="roll">Roll Dice</button>
      <div id="results"></div>
    </div>

When the 'Roll Dice' button is clicked, get the player names from the input fields and call the rollDice() function for each player.

const getRandomNumber = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;


const rollDice = () => getRandomNumber(1, 6);

document.getElementById("roll").addEventListener("click", function () {
  // fetch player names from the input fields
  const player1 = document.getElementById("player1").value;
  const player2 = document.getElementById("player2").value;

  // roll dice for both players
  const player1Score = rollDice();
  const player2Score = rollDice();

  // initialize empty string to store result
  let result = "";

  // determine the result
  if (player1Score > player2Score) {
    result = `${player1} won the round`;
  } else if (player2Score > player1Score) {
    result = `${player2} won the round`;
  } else {
    result = "This round is tied";
  }

  // display the result on the page
  document.getElementById("results").innerHTML = `
  <p>${player1} => ${player1Score}</p>
  <p>${player2} => ${player2Score}</p>
  <p>${result}</p>
  `;
});

You can validate the players' name fields and prettify the markup with some CSS. For the purpose of brevity, I'm keeping it simple for this guide.

That is it. You can check out the demo here.

Conclusion

So generating random numbers in JavaScript is not so random after all. All we are doing is taking in some input numbers, using some Math, and spitting out a pseudo-random number.

For most browser-based applications and games, this much randomness is enough and serves its purpose.

That's it for this guide. Stay safe and keep coding like a beast.