Concept
Equality and type coercion
How values are converted between types, and the difference between == and ===.
Equality and type coercion explained
Type coercion is JavaScript converting a value from one type to another automatically, for example turning a number into a string when you write "5" + 1. Loose equality (==) coerces both sides before comparing, while strict equality (===) compares type and value without converting. Most coercion surprises disappear if you use === and convert values explicitly with Number(), String() or Boolean().
How coercion behaves
"5" + 1 // "51" (+ with a string concatenates)
"5" - 1 // 4 (- only works on numbers)
"5" == 5 // true (string converted to number)
"5" === 5 // false (different types)
null == undefined // true, but null == 0 is false
[] + [] // "" (arrays become strings)
NaN === NaN // false; use Number.isNaN(x) or Object.is
Truthy and falsy values
In an if or with && and ||, values are coerced to booleans. The falsy values are false, 0, -0, 0n, "", null, undefined and NaN. Everything else is truthy, including "0", [] and {}.
Common mistakes
- Using
||for defaults when 0 or an empty string is valid:count || 10replaces 0. Usecount ?? 10, which only replacesnullandundefined. - Adding form values read from inputs: they are strings, so
a + bconcatenates. Convert withNumber()first. - Checking for NaN with
===, which is always false. - Relying on
==with mixed types in comparisons that matter.
What interviewers ask about type coercion
- "
==versus===?" Loose equality converts types first; strict equality does not. - "List the falsy values." The eight above.
- "Why is
[] == falsetrue but[]truthy?"==converts both to numbers (0 and 0), while anifjust checks truthiness, and objects are always truthy.
What should you learn before Equality and type coercion?
- Data typesThe primitive and object types a value can have, and how typeof reports them.
Connections to other concepts
- Part of
- JavaScript
Practise Equality and type coercion
- JavaScript Interview Questions for Freshers3 questions on Equality and type coercion
- Top 20 JavaScript interview questions with answers: core JS, Node.js and React1 question on Equality and type coercion
- Advanced JavaScript Interview Questions1 question on Equality and type coercion