== vs === Equality Operators

Difficulty: Beginner

Question

What is the difference between == and === in JavaScript? When should you use each?

Answer

The == (loose equality) operator compares values after performing type coercion, meaning it converts operands to the same type before comparing. The === (strict equality) operator compares both value and type without any coercion.

Best practice: Always use === (strict equality) to avoid unexpected bugs from type coercion. Use == only when you intentionally want type coercion (e.g., checking for null or undefined with value == null).

Code examples

Loose vs Strict Equality

// Loose equality (==) - performs type coercion
console.log(5 == "5");      // true (string coerced to number)
console.log(0 == false);     // true (false coerced to 0)
console.log("" == false);    // true (both coerced to 0)
console.log(null == undefined); // true (special rule)

// Strict equality (===) - no coercion
console.log(5 === "5");      // false (different types)
console.log(0 === false);     // false (number vs boolean)
console.log("" === false);   // false (string vs boolean)
console.log(null === undefined); // false (different types)

With ==, JavaScript tries to convert both sides to the same type. With ===, types must match.

Common Pitfalls

// Surprising coercion results
console.log([] == false);    // true
console.log([] == ![]);      // true (both coerce to 0)
console.log("0" == false);   // true
console.log("" == 0);        // true
console.log(NaN == NaN);      // false (NaN is never equal to anything)
console.log(NaN === NaN);     // false

// Safe null/undefined check
let val = null;
console.log(val == null);       // true
console.log(val == undefined);  // true
console.log(val === null);      // true
console.log(val === undefined); // false

The == null check is a common pattern to test for both null and undefined in one expression.

Key points

Concepts covered

Equality, Type Coercion, Strict Comparison, Loose Comparison