While this topic may appear basic and familiar but I think we've all been there, using ==
when ===
was the better choice, only to wonder why our code behaves strangely.
So no "ugh you didn't even know this silly, it was so simple" comments please and let's unravel the mysteries of JavaScript's equality operators together.
Loose Equality
The loose equality operator ==
is designed for type coercion (datatype conversion), allowing JavaScript to convert operands to a common type BEFORE comparison.
While this can be convenient, it can also lead to subtle bugs.
Example 1: String and Number
const a = 10;
const b = '10';
console.log(a == b) // Result: true
Even though
a
is a number andb
is a string, we get true. This is because the type of the variablea
is converted to a string before making the comparison.After the comparison, the value is checked in both the variables. If it's same, we will get true otherwise we will get false.
But that's not a problem, at least the values are same?
Haha, just wait for it..
Example 2: NaN Comparison
NaN == NaN; // Result: false
Due to the complexities of
NaN
, using==
to compareNaN
values will ALWAYS return false.For
NaN
checks, useisNaN()
or a strict comparison:===
.
Example 3: String and Boolean
const a = true;
const b = 'true';
console.log(a == b)
If you thought the answer is true, unfortunately that's not correct.
Surprised huh?
If either operand is a Boolean, it will be converted to a number (true becomes 1 and false becomes 0).
Now, you know why the answer was true, not false in the above example.It is because the value of the variable
a
(true) gets converted to a number before the comparison. So after comparison, we're basically comparing1
and'true'
hence we get false because the variables contain different values.
Pretty unexpected behavior, I TOLD YOU.
Hence many experienced developers favor strict equality operator ===
for its strictness, as it reduces ambiguity and encourages explicit type handling.
Strict Equality
The strict equality operator ===
is, well, very strict. It compares both value and type, making it more predictable and less prone to unexpected results.
Example 1: String and Number
"5" === 5; // Result: false
Since the types are different, the comparison returns false
.
Example 2: Boolean and Number
false === 0; // Result: false
In this case, false and 0 have different types, so the comparison is false
.
Conclusion
In JavaScript, clarity and predictability are vital. While loose equality operator can be convenient, it introduces potential pitfalls and surprises. The choice between ==
and ===
depends on your intent and having knowledge of both of the operators is must but there are reasons you should avoid using ==
in your code as we discussed above.
Hope it helps!
For more such content feel free to connect with me.
LinkedIn: https://www.linkedin.com/in/quratulain
GitHub: https://github.com/QuratAin