JavaScript - 29
JavaScript - 29: Guess the Number Game
Create a number guessing game where the computer chooses a number from 1 to 100.
Your challenge: Compare the user's guess with the secret number and show whether the guess is too high, too low, or correct.
Create the secret number
Use: Math.floor(Math.random() * 100) + 1
This creates a random whole number from 1 to 100.
Compare the guess
Use an if / else if / else statement.
If the guess matches randomNumber, show a success message.
If the guess is smaller, show Too low!. Otherwise, show Too high!.
Count attempts
Increase attempts each time the Guess button is clicked.
When the user guesses correctly, include the number of attempts in the message.
Try it: Keep guessing and use the hints to narrow down the secret number.
Good JavaScript habit: Convert input values to numbers before comparing them with numeric values.
👀 Show Solution
let randomNumber = Math.floor(Math.random() * 100) + 1;
let attempts = 0;
const guessInput = document.getElementById("guessInput");
const guessBtn = document.getElementById("guessBtn");
const message = document.getElementById("message");
guessBtn.addEventListener("click", function() {
const userGuess = Number(guessInput.value);
attempts++;
if (userGuess === randomNumber) {
message.textContent =
`Correct! You guessed it in ${attempts} attempts!`;
} else if (userGuess < randomNumber) {
message.textContent = "Too low! Try higher.";
} else {
message.textContent = "Too high! Try lower.";
}
guessInput.value = "";
guessInput.focus();
});Each guess is compared with the secret number, and the message gives the user a hint until the correct number is found.
