Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In if statement,undefined equals with false

I'm confused with the code below:

if(undefined){
   //code will not be executed
}

and

if(!undefined){
   //code will be executed
}

Is that mean the "undefined" equals with false?

Here the question related,but no one point above situation out.

like image 243
Xheldon Cao Avatar asked May 11 '16 15:05

Xheldon Cao


People also ask

Does undefined equal to false?

The Boolean value of undefined is false. The value of Not only undefined but also null, false, NaN, empty string is also false.

Why undefined == false is false?

The ECMA spec doc lists the reason that undefined == false returns false. Although it does not directly say why this is so, the most important part in answering this question lies in this sentence: The comparison x == y, where x and y are values, produces true or false.

Is undefined considered false in JavaScript?

There are only six falsey values in JavaScript: undefined , null , NaN , 0 , "" (empty string), and false of course.


1 Answers

It means that undefined is a falsy value, list of falsy values are:

""        // Empty string
null      // null
undefined // undefined, which you get when doing: var a;
false     // Boolean false
0         // Number 0
NaN       // Not A Number eg: "a" * 2

If you negate a falsy value you will get true:

!""        === true
!null      === true
!undefined === true
!0         === true
!NaN       === true

And when you nagate a truthy value you will get false:

!"hello" === false
!1       === false

But undefined is not equal false:

undefined === false // false
undefined  == false // false

And just for the fun if it:

undefined == null // true
like image 157
Andreas Louv Avatar answered Sep 24 '22 21:09

Andreas Louv