0

I spent a lot of time searching and debugging, but I just can't figure out why does the while loop stop upon "guessing", when my variable is a string...

const myName = 'Daniel';

let guess = prompt("Guess my name!");
while (guess !== myName) {
    guess = prompt("That's incorrect. Guess again!");
}
console.log("Congrats! You guessed my name!")

...but not when it's an integer.

const myAge = 28;

let guess = prompt("Guess my age!");
while (guess !== myAge) {
    guess = prompt("That's incorrect. Guess again!");
}
console.log("Congrats! You guessed my age!")

The popups are keep coming, even though I enter the correct answer. What am I doing wrong?

(I know I could just make 28 a string, but I still don't understand why won't the 2nd snippet work.)

MrDanielHarka
  • 3
  • 1
  • 1
  • 3

1 Answers1

0

Because !== includes type checking and you are simply comparing a string "28" to an integer 28, which is not the same. Either change your value comparison to !=, cast the integer to a string - so const myAge = '28';, or cast the user's input to an integer using parseInt() if you are sure you want to validate an integer input.

You will get a string from the user input. Always. Not an integer.

marks
  • 1,301
  • 3
  • 16