Comparison operators evaluate expressions and return a boolean result. JavaScript distinguishes between Strict Equality (===) (no type coercion) and Loose Equality (==) (implicitly converts operands to matching types before comparing).
flowchart TD
Comp["a === b vs a == b"] --> StrictCheck{"Is Strict (===) used?"}
StrictCheck -- "Yes" --> SameType{"Are Types Identical?"}
SameType -- "No" --> RetFalse["Return false"]
SameType -- "Yes" --> CheckVal["Compare Primitive Values or Heap Memory Address"]
StrictCheck -- "No (==)" --> Coerce["Perform Abstract Equality Coercion Rules"] --> CheckVal
| Operator | Name | Type Coercion? | Example | Result |
|---|---|---|---|---|
=== |
Strict Equality | No | 5 === "5" |
false |
!== |
Strict Inequality | No | 5 !== "5" |
true |
== |
Loose Equality | Yes | 5 == "5" |
true |
!= |
Loose Inequality | Yes | 5 != "5" |
false |
Object.is() |
Same-Value Equality | No | Object.is(NaN, NaN) |
true (Strict equality returns false) |
// Demonstrating Loose vs Strict Equality traps and Object Identity
// 1. Strict vs Loose Comparison Traps
console.log("--- Primitive Comparison Traps ---");
console.log(`0 == false: ${0 == false}`); // true (Coercion)
console.log(`0 === false: ${0 === false}`); // false (Strict)
console.log(`"" == 0: ${"" == 0}`); // true (Coercion)
console.log(`null == undefined: ${null == undefined}`); // true (Special loose rule)
console.log(`null === undefined: ${null === undefined}`);// false
// 2. Object Reference Identity
const objA = { id: 10 };
const objB = { id: 10 };
const objC = objA;
console.log("
--- Object Reference Comparison ---");
console.log(`objA === objB (Identical structure): ${objA === objB}`); // false (Different memory address!)
console.log(`objA === objC (Shared reference): ${objA === objC}`); // true
// 3. Object.is() for Edge Cases
console.log("
--- Object.is() vs Strict === ---");
console.log(`NaN === NaN: ${NaN === NaN}`); // false
console.log(`Object.is(NaN, NaN): ${Object.is(NaN, NaN)}`); // true
console.log(`-0 === +0: ${-0 === +0}`); // true
console.log(`Object.is(-0, +0): ${Object.is(-0, +0)}`); // false
=== and !==: Avoid loose == equality in application code to prevent obscure bugs caused by coercion.val == null: The ONLY widely accepted exception for loose equality is val == null, which conveniently matches both null and undefined.Object.is() for NaN: Use Object.is(a, b) when explicitly testing for NaN equality or distinguishing -0 from +0.Explain why [] == false evaluates to true while [] === false evaluates to false.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.