0

So I am a beginner at Javascript so please help me understand this!

I was just testing out different things with if/else and prompt(), and when I wrote the codes below:

let ask = Number(prompt("Type a number"));

if (ask != NaN) {
  alert(`You typed ${ask}`);
} else {
  alert("You typed a word")
}

so the code is working well until I type in a word. when I type a number (for instance: 12) it shows "You type 12" but when I typed a word (for instance "cat"), it shows "You typed NaN". but why? I know "cat" is a NaN but why is it not showing the else statement? (You typed a word).

please help!

lejlun
  • 4,140
  • 2
  • 15
  • 31
  • 1
    because ... `NaN != NaN` ... it's a quirk of Javascript - use `isNaN` – Bravo Aug 07 '21 at 12:16
  • @lejlun - The OP's `ask` would always pass that check, since they do `Number(prompt(...))`. – T.J. Crowder Aug 07 '21 at 12:20
  • @Saad - Beware that `Number("")` is `0`. I go through your various options for converting strings to numbers in [this answer](https://stackoverflow.com/questions/28994839/why-does-string-to-number-comparison-work-in-javascript/28994875#28994875). Happy coding! – T.J. Crowder Aug 07 '21 at 12:22
  • @Bravo - Indeed. :-) But just FWIW, JavaScript gets this behavior from IEEE-754 floating point numbers (which JavaScript uses). Java, C#, and (most) others that use `double` have the same behavior. – T.J. Crowder Aug 07 '21 at 12:29

0 Answers0