JavaScript Interview Question: == vs ===
Short answer: === (strict equality) compares value and type with no conversion. == (loose equality) converts the operands to a common type first, which leads to surprising results.
1 === '1' // false - different types
1 == '1' // true - '1' converted to 1
0 == '' // true
0 == '0' // true
'' == '0' // false (not transitive!)
false == '0' // true
null == undefined // true
null == 0 // false
NaN == NaN // false (NaN is never equal to anything)
Rule of thumb
Always use === and !==. Linters (eqeqeq) can enforce it.
The one common exception
if (value == null) { ... } // true for both null and undefined
Some teams allow this idiom; value ?? fallback often expresses the intent better.
Objects compare by reference
({ a: 1 }) === ({ a: 1 }) // false - two different objects
const x = { a: 1 }; x === x // true
Bonus: Object.is
Object.is(NaN, NaN) // true
Object.is(0, -0) // false (=== says true)
React uses Object.is to decide whether state has changed.
Was this article helpful?
Comments
No comments yet. Have a question or a tip? Be the first to share it.