Unays Learn ยท JavaScript

Project: a number guessing game in JavaScript

Games are a great way to practise programming. In this project you will build a number guessing game step by step, using variables, conditions, events and the DOM.

Plan the game

Before coding, write the rules in plain words:

  1. The computer picks a whole number from 1 to 100.
  2. The player types a guess and presses "Guess".
  3. The game says "Too high", "Too low" or "Correct" and counts the guesses.
  4. After a correct guess, the player can start again.

Each rule becomes a small piece of code. Planning first makes the program much easier to write.

Random whole numbers

function randomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

console.log(randomInt(1, 100));

Math.random() gives a decimal from 0 up to (but not including) 1. Multiplying by 100 and rounding down with Math.floor gives 0 to 99, and adding 1 shifts it to 1 to 100.

The page

<h1>Guess the number</h1>
<p>I am thinking of a number from 1 to 100.</p>
<form id="game">
  <label for="guess">Your guess</label>
  <input id="guess" type="number" min="1" max="100" required>
  <button id="submit">Guess</button>
</form>
<p id="message" role="status"></p>
<button id="again" hidden>Play again</button>

The game logic

<script>
  const form = document.querySelector("#game");
  const input = document.querySelector("#guess");
  const message = document.querySelector("#message");
  const again = document.querySelector("#again");
  const submit = document.querySelector("#submit");

  let secret, guesses;

  function newGame() {
    secret = Math.floor(Math.random() * 100) + 1;
    guesses = 0;
    message.textContent = "";
    input.value = "";
    input.disabled = submit.disabled = false;
    again.hidden = true;
    input.focus();
  }

  form.addEventListener("submit", event => {
    event.preventDefault();
    const guess = Number(input.value);
    if (!Number.isInteger(guess) || guess < 1 || guess > 100) {
      message.textContent = "Please enter a whole number from 1 to 100.";
      return;
    }
    guesses++;
    if (guess > secret) message.textContent = guess + " is too high.";
    else if (guess < secret) message.textContent = guess + " is too low.";
    else {
      message.textContent = "Correct! You found it in " + guesses + (guesses === 1 ? " guess." : " guesses.");
      input.disabled = submit.disabled = true;
      again.hidden = false;
      again.focus();
    }
    input.select();
  });

  again.addEventListener("click", newGame);
  newGame();
</script>

Notice the input check comes first: never trust that the value is what you expect, even with min and max on the input.

A clever strategy

If you always guess the middle of the remaining range (50, then 25 or 75, and so on), you never need more than 7 guesses, because each guess halves the possibilities and 27 = 128 is more than 100. This is exactly the idea behind binary search.

Try it yourself

Build the game in Unays Code. Then add a difficulty choice (1 to 10, 1 to 100, 1 to 1000), a list of previous guesses, and a "best score" saved in localStorage.

This tutorial was written with AI assistance and reviewed by Unays. The runnable code examples were tested before publishing. Spotted a mistake? Tell us at [email protected].