1.1K
In t his example we present a number guessing game
Example(s)
function guessNumber() { // generating a random integer from 1 to 5 const random = Math.floor(Math.random() * 5) + 1; // get input from the user let number = parseInt(prompt('Guess a number from 1 to 5: ')); // get the input until the guess is correct while(number !== random) { number = parseInt(prompt('Guess a number from 1 to 5: ')); } // check if the guess is correct if(number == random) { console.log('You guessed the correct number.'); } } // call the function guessNumber();
In the above program, the guessNumber() function is created where a random number from 1 to 5 is generated using Math.random() function.
The user is prompted to guess a number from 1 to 5.
The parseInt() converts the numeric string value to an integer value.
The while loop is used to take input from the user until the user guesses the correct answer.
The if else statement is used to check the condition. The equal to == operator is used to check if a guess is correct.
Now the example above is Ok but doesn't give any feedback – lets see a better one
function guessGame() { let randomNumber = Math.floor(Math.random() * 11); //console.log(randomNumber) let guess; do { guess = +prompt("Guess number 1-10"); console.log(guess); if (randomNumber > guess) { console.log("You guessed too low"); } else if (randomNumber < guess) { console.log("Guess was too high"); } } while (guess !== randomNumber); console.log("You Won"); } guessGame();
Run this in the console and you will see feedback
5 Guess was too high 3 Guess was too high 2 You Won
Alternatives
Some alternatives to try out
var randomNumber = Math.floor(Math.random() * 6 ) + 1; var guess = prompt('I am thinking of a random number between 1 and 6. What is it?'); if (parseInt(guess) === randomNumber ) { document.write('<p>You guessed the number!</p>'); } else { document.write('<p>Sorry. The number was ' + randomNumber + '</p>'); }