Why == and === behave differently in JavaScript
Source: Dev.to
Strict Equality (===)
=== checks two things:
- Are the values the same?
- Are the types the same?
Both conditions must be met.
5 === 5 // true
5 === "5" // false
true === 1 // false
null === undefined // false
If the types don’t match, JavaScript returns false without any conversion.
Loose Equality (==)
== tries to be “helpful” by converting values before comparing them (type coercion).
5 == "5" // true (string → number)
true == 1 // true (boolean → number)
false == 0 // true
null == undefined // true (special case)
Some surprising cases
"" == 0 // true
"0" == 0 // true
[] == 0 // true
Why This Happens
When using ==, JavaScript automatically attempts to make the operands the same type:
| Conversion | From → To |
|---|---|
| strings → numbers | "5" → 5 |
| booleans → numbers | true → 1 |
| arrays → strings | [] → "" |
null / undefined | only equal to each other |
These implicit steps are why == can produce confusing results.
Which One Should You Use?
For beginners—and in most cases—prefer strict equality:
// Use ===
It’s predictable and avoids unexpected type coercion.
Use == only when you fully understand the conversion rules or need the special case null == undefined.
Simple Demo
console.log(0 == false); // true
console.log(0 === false); // false
console.log("5" == 5); // true
console.log("5" === 5); // false
Running these snippets in the console shows the difference instantly.
Quick Summary
| Comparison | Checks Type? | Converts Values? | Example |
|---|---|---|---|
=== | Yes | No | "3" === 3 → false |
== | No | Yes | "3" == 3 → true |
Short version
===is strict and predictable.==performs type coercion and can be messy.
Use === for cleaner logic and fewer surprises.