When I compare undefined and null against Boolean false, the statement returns false:
undefined == false; null == false;
It return false. Why?
The Boolean value of undefined is false. The value of Not only undefined but also null, false, NaN, empty string is also false.
Description. A falsy value is something which evaluates to FALSE, for instance when checking a variable. There are only six falsey values in JavaScript: undefined , null , NaN , 0 , "" (empty string), and false of course.
Both undefined and null are falsy by default. So == returns true. But when we use the strict equality operator (===) which checks both type and value, since undefined and null are of different types (from the typeof Operator section), the strict equality operator returns false.
undefined is true because undefined implicitly converts to false , and then ! negates it. Collectively, those values (and false ) are called falsy values. Anything else¹ is called a truthy value.
With the original answer pointing to the spec being deleted, I'd like to provide a link and short excerpt from the spec here.
http://www.ecma-international.org/ecma-262/5.1/#sec-11.9.3
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.
If we look up the definition for null, we find something like this:
NULL or nil means "no value" or "not applicable".
In Javascript, undefined
is treated the same way. It is without any value. However, false does have a value. It is telling us that something is not so. Whereas undefined
and null
are not supposed to be giving any value to us. Likewise, there is nothing it can convert to for its abstract equality comparison therefore the result would always be false. It is also why null == undefined
returns true (They are both without any value). It should be noted though that null === undefined
returns false because of their different types. (Use typeof(null)
and typeof(undefined)
in a console to check it out)
What I'm curious of though, is that comparing NaN
with anything at all will always return false. Even when comparing it to itself. [NaN == NaN
returns false]
Also, another odd piece of information: [typeof NaN
returns "number"]
If possible, you should avoid using the == operator to compare two values. Instead use === to truly see if two values are equal to each other. == gives the illusion that two values really are exactly equal when they may not be by using coercion. Examples:
5 == "5"
is true
5 === "5"
is false
"" == false
is true
"" === false
is false
0 == false
is true
0 === false
is false
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With