== vs ===
=== (strict equality)
Compares value and type - no conversion.
js
1 === 1 // true
1 === '1' // false - different types
null === null // true
null === undefined // false== (loose equality)
Compares values after type coercion - JavaScript converts types before comparing.
js
1 == '1' // true - '1' converted to 1
0 == false // true - false converted to 0
null == undefined // true - special rule
null == 0 // false - special rule
[] == false // true - both convert to 0
'' == false // true - both convert to 0The coercion rules are complex
js
[] == ![] // true - this is why == is confusing
// [] -> 0, ![] -> false -> 0Object comparison
js
// both == and === compare references for objects
const a = { x: 1 };
const b = { x: 1 };
a == b // false
a === b // false
a === a // trueAlways use
===. The loose equality rules are confusing, hard to remember, and a common source of bugs. The only exception some teams make isx == nullto check for bothnullandundefinedat once.
updated
did you know it?