1

In Javascript, I found this:

if (!NaN)
     console.log('do sth');

This code works, but if I write:

if (NaN)
     console.log('do sth');

This one is not work. I don't really understand the logic behind this.

mazaneicha
  • 8,794
  • 4
  • 33
  • 52
Tom Riddle
  • 21
  • 2
  • 8
    NaN is falsy. http://stackoverflow.com/questions/22600248/is-nan-falsy-why-nan-false-returns-false. If you would like to check if something is NaN, there's a special function called isNaN https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN – Hypaethral Feb 28 '16 at 03:26
  • 1
    *"I don't really understand the logic behind this"* - Even without knowing what NaN is that code makes sense, because if `!something` is true then logically `something` is false. So (again, even without knowing what NaN is) you would expect one of those console.log() statements to be executed but not the other... – nnnnnn Feb 28 '16 at 04:25

1 Answers1

2

NaN is a special number in JavaScript which is used to symbolize an illegal number a.k.a. Not-A-Number, such as when try to multiply a number with a string, etc.

Now, in JS, there is the concept of falsy values. As you can see NaN is classified as a falsy value.

This is why when you execute the following:

if(NaN) {
  console.log("something");
}

..it doesn't work, because NaN is evaluated to false. And therefore, similarly the if(!NaN) conditional evaluates to true.

Soubhik Mondal
  • 2,666
  • 1
  • 13
  • 19
  • What do you mean by "NaN is a special number"? NaN means "not a number" so it's definitely not a number, especially not a "special number". – Roco CTZ Feb 28 '16 at 03:37
  • 4
    If you check the value of `typeof NaN` you will get `"number"`. Similarly if you check the output of `NaN.constructor.name` you will get `"Number"`. Hence, why I said it's a special number. – Soubhik Mondal Feb 28 '16 at 03:39
  • 1
    @RocoCTZ - Try `typeof NaN`. You'll see it's a "number". – jfriend00 Feb 28 '16 at 03:39
  • Thanks Blaze. Now I understand the falsy values part. Never heard about it before. – Tom Riddle Feb 29 '16 at 04:16