Home > Back-end >  How do I close a prompt upon clicking cancel in JS?
How do I close a prompt upon clicking cancel in JS?

Time:06-18

I cannot for the life of me figure out how to close the prompt altogether upon pressing cancel in my code for a guessing game. I've tried several things, but each time either the code ignores what I'm trying to do, or ends in an error. Here's the code in question:

let numGuess = prompt (`Guess the number I am thinking of (between 1 and 10):`);
let num = (4);

let numTries = 1

console.log(numGuess);

numGuess = parseInt(numGuess)

if (prompt == null) {

alert (`Press F5 to play again.`) 


}
if (numGuess === num) {

  alert (`Correct! You guessed the number in 1 try! Press F5 to play again.`);

}

else while ((numGuess !== num) && (numTries <3))

{

  numTries = numTries  

  alert (`Incorrect guess. Try again.`)

}

CodePudding user response:

Check for the user input value, not for prompt. And also don't use while loop here .Loop is used for the traverse.

let numGuess = prompt (`Guess the number I am thinking of (between 1 and 10):`);
let num = (4);

let numTries = 1

console.log(numGuess);

numGuess = parseInt(numGuess)

if (!numGuess) {

alert (`Press F5 to play again.`) 


}
else if (numGuess === num) {

  alert (`Correct! You guessed the number in 1 try! Press F5 to play again.`);

}

else{
  numTries = numTries  

  alert (`Incorrect guess. Try again.`)

}

CodePudding user response:

The main issue with your code is using " " after numTries which make the numTries variable value doesn't change and the while loop continues working without stopping, you need to insert it before. ex:

  numTries

The code below is a working example of what you want to do.

let numGuess;
let numTries = 0;
let num = 4;
const guessFunction = () => {
    if (numTries >= 3) {
        alert("Sorry you Failed in the 3 tries! Press F5 to play again.");
        return;
    }
    numGuess = parseInt(
        prompt(`Guess the number I am thinking of (between 1 and 10):`)
    );
    numTries =   numTries
    if (numGuess === num) {
        alert(`Correct! You guessed the number in ${numTries} try! Press F5 to play again.`);
        return;
    }
    if(numTries <= 2) {
        alert(`Incorrect guess. Try again.`);
    }
    guessFunction()
};

guessFunction()

  • Related