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 convertsnullto0before making the comparison. So,null >= 0becomes0 >= 0, which istrue.Strict Equality (
===): The strict equality operator does not perform type conversion, sonull === 0isfalsebecausenullis 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,undefineddoes not get converted to0during comparison. Instead, the result is alwaysfalsebecauseundefinedis considered "not a number" in this context.Equality Operator (
==): Even when using the loose equality operator,undefineddoes not equal0. In fact,undefinedis only equal tonullwhen using==.
Understanding == vs ===
==(Loose Equality): This operator converts the operands to the same type before making the comparison. This is whynull == 0isfalse, butnull == undefinedistrue.===(Strict Equality): This operator checks both the value and the type, without any conversion. This is whynull === 0isfalse, andnull === undefinedis 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 ===.