JavaScript Fundamentals: Understanding Equality (== vs ===)
Welcome to the fourth part of our Node.js Jumpstart series! In Variables and Functions we covered key JS fundamentals. Now, let's tackle a concept that frequently causes bugs: comparing with == vs. ===.
Understanding == vs === (Loose vs. Strict Equality)
This difference is a common source of subtle bugs. JavaScript offers two equality checks:
-
Loose Equality (
==): Compares values after type coercion. Example:console.log(5 == '5'); // true console.log(0 == false); // true console.log(null == undefined); // true console.log('' == false); // true -
Strict Equality (
===): Compares both type and value without coercion. Example:console.log(5 === '5'); // false console.log(0 === false); // false console.log(null === undefined); // false console.log('' === false); // false
Things in life may not be equal.
But in JavaScript? Everything might be... if you use
==instead of===.
Recommendation: Always use === (and !==) to avoid unexpected coercion. Save == (!=) for rare, explicit cases like when you're comparing null to undefined.
What About Objects and Arrays?
One important gotcha: == and === compare objects and arrays by reference, not by value.
const a = [1, 2, 3];
const b = [1, 2, 3];
console.log(a == b); // false
console.log(a === b); // false
const c = a;
console.log(a === c); // true (same reference)
Two arrays with identical contents are not equal unless they point to the exact same object in memory. To compare object/array contents, use JSON.stringify() or a deep-equality library.
Quick Reference
| Expression | == | === |
|---|---|---|
5 == '5' | true | false |
0 == false | true | false |
null == undefined | true | false |
'' == false | true | false |
[] == false | true | false |
Now that you're equipped with solid equality knowledge, let's explore some of the most common JavaScript quirks and concepts that trip up even experienced developers.