CodeOath
← All posts
JavaScript60 min total · 16 parts

JavaScript Array and Object Methods Cheat Sheet

Part 11 of 16 · ~2 min

Equality: == vs. ===, and Comparing Two Objects

=== (strict equality) checks that the type and the value both match, and never converts either side to force an answer. == (loose equality) pushes both sides toward a shared type before comparing them, following a set of coercion rules that are genuinely hard to hold in your head:

"82" == 82;          // true — the string is coerced to the number 82
0 == "";              // true — "" coerces to 0
0 == false;            // true — false coerces to 0
null == undefined;    // true — a special-cased pair; null === undefined is false
[] == false;           // true — [] becomes "" via toString, then "" becomes 0

Nearly every style guide lands on the same practical advice: reach for === as the default, without exception. The one place == earns its keep is x == null, since a loose comparison against null happens to also catch undefined — sparing you from writing x === null || x === undefined out longhand.

There's something worth internalizing about both operators together: neither one ever looks inside an array or object to compare what's there. Once you're past primitive values, == and === alike are only ever asking one narrower question — is this literally the same object sitting in memory:

candidates[0] === candidates[0]; // true — the exact same object reference

const priyaCopy = { ...candidates[0] };
priyaCopy === candidates[0]; // false — same fields, same values, different object

candidates.slice(0, 1)[0] === candidates[0]; // true — .slice() copies the ARRAY, not the objects inside it

That last line is worth sitting with. .slice(), spread, .filter() — every array copying method in this reference makes a new array, but the objects sitting inside that array are the same objects, by reference, as the ones in the original. Two API calls that each independently fetch "the same candidate" will never produce ===-equal objects, even with identical data, because each response built its own fresh object.

To actually find out whether two records hold the same data, you've got three real options: write the field-by-field check by hand, compare JSON.stringify(a) against JSON.stringify(b) (quick, but it cares about the order keys were written in and quietly mishandles functions, undefined, or dates), or bring in a genuine deep-equality function — Lodash's isEqual covers most cases people reach for one.