Let's build a proper game! The computer picks a secret number from 1 to 100, and you have to guess it. After each guess, it tells you whether to go higher or lower. This one uses prompt and alert, so run it in the browser (put it in your script.js and open index.html).
const secret = Math.floor(Math.random() * 100) + 1;
let attempts = 0;
let guessedIt = false;
alert("🎯 I'm thinking of a number from 1 to 100. Can you guess it?");
while (!guessedIt) {
const input = prompt("Your guess:");
// The user clicked "Cancel"
if (input === null) {
alert(`Giving up? The number was ${secret}. Better luck next time!`);
break;
}
const guess = Number(input);
// Not a valid number? Don't count it, just ask again.
if (Number.isNaN(guess) || guess < 1 || guess > 100) {
alert("Please type a whole number from 1 to 100.");
continue;
}
attempts++;
if (guess < secret) {
alert(`${guess} is too low! Go higher ⬆️`);
} else if (guess > secret) {
alert(`${guess} is too high! Go lower ⬇️`);
} else {
guessedIt = true;
alert(`🎉 YES! ${secret} is right! You got it in ${attempts} ${attempts === 1 ? "try" : "tries"}.`);
}
}
Look at everything this tiny game uses: variables, random numbers, type conversion, a while loop, break, continue, if/else if/else, logical operators, template literals and the ternary operator. That's basically everything from Elementary School in one program!
The best strategy is to always guess the middle of the remaining range. Start with 50. If it's too low, try 75. If that's too high, try 62. And so on. With this strategy, you'll always find the number within 7 guesses. Computer scientists call this binary search, and it's one of the most important ideas in programming.
Upgrade the game! Some ideas:
- Give the player a maximum of 10 attempts. If they run out, they lose.
- Let the player choose the difficulty: 1–10 (easy), 1–100 (medium) or 1–1000 (hard).
- After the game ends, use
confirmto ask "Play again?", and wrap the whole game in another loop.
🎓 Congratulations! You've graduated from Elementary School! 🎓
Take a moment to appreciate how far you've come. You can now store information, work with text and numbers, do math, make decisions, and repeat things. With just these tools, you could write a surprisingly large number of real programs.
But as your programs get bigger, they'll start getting messy. Really messy. In Middle School, you'll learn the three big tools for keeping code organized: functions, arrays and objects. Grab your backpack. The big kids are waiting.