13

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.

Community
  • 1
  • 1
Xheldon Cao
  • 217
  • 1
  • 2
  • 11

3 Answers3

30

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
andlrc
  • 41,466
  • 13
  • 82
  • 108
  • 1
    I am shocked that `undefined == false` gives `false`! How come? Where I can read about it? – Marecky Jul 08 '20 at 11:54
  • @Marecky there is a nice write up on https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness – andlrc Jul 30 '20 at 18:13
7

In javascript strict mode, undefined is not false, but javascript try to convert the object or var to a boolean value (this is called in javascript truthy value), that's the reason you got an undefined as false. This happens with null also, for example.

You can force that with this strict no equality:

if(undefined!==false) console.log("Is not false"); 
1

Please take a look below checked falsy values:

""==false?
    Ans: true
null == false?
    Ans: false
undefined == false?
    Ans: false
0 == false?
    Ans: true
NaN == false?
    Ans: false
null == NaN?
    Ans: false

We can see that null == false,undefined == false,null == NaN, and NaN == false are not true That means they are not equal. From the above result, we got 3 falsy values group:

  1. The False group
  2. The Null group and
  3. The NaN group

But a negative falsy value is always true:

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

For example: To check true value of dataTitle variable

if(dataTitle && (dataTitle != null))
{
    console.log('hi');
}

The above statement will check the false group as well as the null group

To check false value of dataTitle variable

if(!dataTitle)
{
    console.log('hi');
}

//or 

if(dataTitle==null || dataTitle===false)
  console.log('hi');
Bablu Ahmed
  • 2,638
  • 1
  • 26
  • 46