Tom Riddle
Tom Riddle

Reputation: 21

NaN in Javascript

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.

Upvotes: 1

Views: 832

Answers (1)

Soubhik Mondal
Soubhik Mondal

Reputation: 2666

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.

Upvotes: 2

Related Questions