Skip to content
BetaDE
Lesson 7 of 11JavaScript

JavaScript · Lesson 7 · 35 minutes

Project: guess the number

What you'll learn

  • Ask for input with prompt()
  • Turn text into numbers with Number()
  • Build a complete game with while, if and counters

prompt(): asking questions

With prompt() JavaScript asks for something. Here an input field appears below the editor for it:

const name = prompt("What's your name? ");
console.log(`Hello ${name}!`);

Careful: input is text

prompt() always returns text – even if you type a number. Number() turns it into a real number:

const text = "12";
console.log(text + 1);           // text + number = "121"
console.log(Number(text) + 1);   // 13

Python comparison: this is like int(input(...)) in Python.

The game

This is how a number guessing game with a random number works – Math.random() gives a number between 0 and 1:

const secret = Math.floor(Math.random() * 20) + 1;
let guess = 0;
let guesses = 0;

while (guess !== secret) {
  guess = Number(prompt("Number from 1 to 20: "));
  guesses++;
  if (guess < secret) console.log("too small");
  else if (guess > secret) console.log("too big");
}
console.log(`Done in ${guesses} ${guesses === 1 ? "guess" : "guesses"}!`);

In the task the secret number is fixed (7) so that the automatic check knows what has to come out.

Keep building: limit the guesses to 5 – or print with every guess how far off it still is.

Your task

Your turn

Finish the number guessing game. The secret number is secret. Keep asking with prompt("Your guess: ") until the guess is right. After every wrong guess print too small or too big. At the end: Correct! Guesses: 3 (with the real number).

const secret = 7;
let guesses = 0;

// Ask for guesses in a loop here

Solve it without hints to earn a ⭐ on your progress page.

Show solution

Try it yourself first – mistakes teach you the most. Here is one possible solution:

const secret = 7;
let guesses = 0;
let guess = 0;

while (guess !== secret) {
  guess = Number(prompt("Your guess: "));
  guesses++;
  if (guess < secret) {
    console.log("too small");
  } else if (guess > secret) {
    console.log("too big");
  }
}
console.log(`Correct! Guesses: ${guesses}`);