In if statement,undefined equals with false
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");
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:
- The False group
- The Null group and
- 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');
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