Reputation: 337
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.
Upvotes: 24
Views: 46952
Reputation: 2932
In javascript, undefined
and null
are empty properties declared on the global scope.
Their value doesn't equal false
; they both have the initial value of primitive undefined.
undefined == false // false
With that said, both will result in false
value upon a programmatic true/false evaluation. In your example, you used a logical NOT operator (MDN):
Returns false if its single operand can be converted to true; otherwise, returns true
The negation operator first evaluated undefined
as false
, and then negated the value to true
. You can illustrate the process roughly like this:
if (!(!!undefined)) {
// code will be executed
}
Upvotes: 0
Reputation: 47099
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
Upvotes: 48
Reputation: 5010
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:
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');
Upvotes: 1
Reputation: 346
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");
Upvotes: 7