JavaScript comparisons can sometimes be tricky, especially when dealing with different data types like null
and undefined
. Today, we’ll explore how comparison operators work and the nuances between ==
and ===
in JavaScript.
Basic Comparisons
Let’s start with some basic comparisons:
console.log(2 > 1); // true
console.log(2 >= 1); // true
console.log(2 < 1); // false
console.log(2 == 1); // false
console.log(2 != 1); // true
These comparisons are straightforward and work as you would expect. But things get interesting when we introduce null
and undefined
into the mix.
Comparing null
with Numbers
Let’s see what happens when we compare null
with numbers:
console.log(null >= 0); // true
console.log(null === 0); // false
Here’s what’s happening:
Comparison Operator (
>=
): When you use a comparison operator like>=
, JavaScript convertsnull
to0
before making the comparison. So,null >= 0
becomes0 >= 0
, which istrue
.Strict Equality (
===
): The strict equality operator does not perform type conversion, sonull === 0
isfalse
becausenull
is not the same type as0
.
Comparing undefined
with Numbers
Now, let’s look at how undefined
behaves:
console.log(undefined >= 0); // false
console.log(undefined == 0); // false
Comparison with
undefined
: Unlikenull
,undefined
does not get converted to0
during comparison. Instead, the result is alwaysfalse
becauseundefined
is considered "not a number" in this context.Equality Operator (
==
): Even when using the loose equality operator,undefined
does not equal0
. In fact,undefined
is only equal tonull
when using==
.
Understanding ==
vs ===
==
(Loose Equality): This operator converts the operands to the same type before making the comparison. This is whynull == 0
isfalse
, butnull == undefined
istrue
.===
(Strict Equality): This operator checks both the value and the type, without any conversion. This is whynull === 0
isfalse
, andnull === undefined
is alsofalse
.
Wrapping Up
Understanding how JavaScript handles comparisons is crucial for avoiding unexpected behavior in your code. Whether you’re comparing numbers, dealing with null
or undefined
, or deciding between ==
and ===
, knowing the details will help you write more predictable and reliable JavaScript.
Happy coding and see you in the next one!!!
Top comments (1)
Another possibility for comparisons is Object.is(), which gives different results from ===.