JS Comparisons
In this page:
Loose Equality (==)
The == operator converts both operands to a common type before comparing them, so 5 == 5 is true even though one side is a string and the other a number. This type coercion is convenient in small scripts but has surprised generations of JavaScript developers with unexpected true/false results.
Example: Loose Equality (==)
console.log('5' == 5); // true - type coercion
Strict Equality (===)
The === operator compares both value and type without converting either operand, so 5 === 5 is false because a string can never strictly equal a number. Most style guides recommend === by default since it avoids the surprising coercion bugs that == can introduce.
Example: Strict Equality (===)
console.log('5' === 5); // false - no coercion, different types
Relational Operators
The relational operators <, >, <=, and >= compare numbers by magnitude and compare strings character by character using Unicode code points, which is called lexicographic order. Comparing values of different types with these operators triggers the same kind of coercion that == uses, so it pays to know what you're comparing.
Example: Relational Operators
console.log(5 < 10);
console.log("apple" < "banana"); // lexicographic order
Comparing Different Types
null and undefined are loosely equal to each other but not strictly equal, since they represent different values of different types under the hood. NaN is the only value in JavaScript that is never equal to itself, whether you use == or ===, which is why isNaN() or Number.isNaN() exists specifically to detect it.
Example: Comparing Different Types
console.log(null == undefined); // true
console.log(null === undefined); // false
console.log(NaN === NaN); // false, always
Object.is() and Special Cases
Object.is() behaves like === for almost everything but fixes two edge cases: it correctly reports NaN as equal to itself, and it correctly reports -0 and +0 as different values, whereas === treats them as equal. It's mostly used internally by JavaScript engines and rarely needed in everyday code, but it's worth knowing it exists.
Example: Object.is() and Special Cases
console.log(Object.is(NaN, NaN)); // true, fixes the === quirk
console.log(Object.is(0, -0)); // false, distinguishes +0/-0
console.log(0 === -0); // true
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: