I know that null
is an object with no attributes or functions.
However, I am confused that why console.log(null == false);
and console.log(null == true);
both return false.
What are the conversion rules between null
and boolean
?
I know that null
is an object with no attributes or functions.
However, I am confused that why console.log(null == false);
and console.log(null == true);
both return false.
What are the conversion rules between null
and boolean
?
Answer : There no relative aspect between null and boolean.
MDN Source:-
Javascirpt|MDN
This is because the Abstract Equality Comparison Algorithm requires that if
Type(x)
orType(y)
is a Boolean in the expressionx == y
then the Boolean value should be coerced to a number viaToNumber
, which convertstrue
to 1 andfalse
to+0
.This means that any comparison of
true == something
orsomething == true
results in1 == something
orsomething == 1
(replacingtrue
and1
withfalse
and+0
forfalse
).The Null type does not compare as equal to either 1 or +0 (in fact, null is only comparable to
undefined
in the AECA).There is a detailed discussion of all of the different kinds of equality in JavaScript on MDN that is well worth looking at if you want to know more.
However, if you coerce
null
to a number it is coerced to+0
so+null == false
actually returnstrue
.Adding to the current discussion. null >= false returns true.
I believe that it is because this is interpreted as !(null < false)
The value
null
is a JavaScript literal represents an "empty" value or "undefined".null
is one of JavaScript's primitive values. It is neither equal to booleantrue
nor equal to booleanfalse
because it's value is undefined. The value ofnull
is more inclined towards false even though it is notfalse
. That's why it's called "falsey" operators and anif (var) { }
block does not get executed whenvar
isnull
.