learn deep. ship safe.Practice testsFollow ByteMunSubscribe

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 || 10 replaces 0. Use count ?? 10, which only replaces null and undefined.
  • Adding form values read from inputs: they are strings, so a + b concatenates. Convert with Number() 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 [] == false true but [] truthy?" == converts both to numbers (0 and 0), while an if just checks truthiness, and objects are always truthy.
Concept map
Learn firstData types
Part of JavaScriptEquality and type coercion

What should you learn before Equality and type coercion?

  1. 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

All topics