Skip to main content
Practice Problems

Loose (==) vs strict (===) equality in JavaScript

== vs === in JavaScript

JavaScript has two equality operators: loose equality (==) and strict equality (===). Understanding the difference is essential for writing reliable code.


Strict Equality (===)

Compares value AND type. No type coercion is performed.

javascript
5 === 5; // true 5 === "5"; // false (different types) true === 1; // false null === undefined; // false NaN === NaN; // false (NaN is never equal to itself)

Loose Equality (==)

Compares values after type coercion. JavaScript converts operands to the same type before comparing.

javascript
5 == "5"; // true (string "5" β†’ number 5) true == 1; // true (true β†’ 1) false == 0; // true (false β†’ 0) null == undefined; // true (special rule) "" == 0; // true ("" β†’ 0) "0" == false; // true ("0" β†’ 0, false β†’ 0)

Coercion Rules for ==

ComparisonCoercionResult
number == stringString β†’ Number5 == "5" β†’ true
boolean == anyBoolean β†’ Number firsttrue == "1" β†’ true
null == undefinedAlways trueSpecial rule
null == 0Always falsenull only == undefined
object == primitiveObject β†’ primitive via valueOf/toString

Object Comparison

Both == and === compare objects by reference, not by value:

javascript
const a = { x: 1 }; const b = { x: 1 }; const c = a; a === b; // false (different references) a === c; // true (same reference) a == b; // false (still by reference) [] == []; // false {} == {}; // false

Special Cases

javascript
NaN === NaN; // false NaN == NaN; // false // Use Number.isNaN() or Object.is() instead Object.is(NaN, NaN); // true Object.is(+0, -0); // false (=== gives true)

When to Use Which

OperatorUse When
===Always (default choice)
==Only when checking null == undefined
javascript
// βœ… Common pattern: check for null OR undefined if (value == null) { // value is null or undefined } // Same as: if (value === null || value === undefined) { // value is null or undefined }

Important:

Always use === by default. The only widely accepted use of == is checking for null/undefined in one comparison: if (value == null). ESLint rule eqeqeq enforces this best practice.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.

Finished reading?
Practice Problems