Lesson 89 +15 XP

Type Coercion

Type Coercion

Coercion is when JavaScript converts a value's type automatically.

String coercion

The + operator turns things into strings when one side is a string:

"age: " + 30; // "age: 30"

Numeric coercion

Arithmetic operators other than + try to convert to numbers:

"10" - 2;  // 8
"10" * 2;  // 20
"10" / 2;  // 5

Boolean coercion

Conditions convert values to true or false (truthy/falsy):

if ("hello") { /* runs, string is truthy */ }
if (0) { /* skipped, 0 is falsy */ }

The classic surprises

[] + [];  // "" (both convert to empty strings)
"5" + 2;  // "52" (string wins)
"5" - 2;  // 3 (numbers win)

Avoiding surprises

Use === (strict equality) instead of == so no coercion happens during comparison:

"5" === 5; // false (no coercion)
"5" == 5;  // true (coerced)

TL;DR

  • Coercion is automatic type conversion.
  • + leans to strings; - * / lean to numbers.
  • Conditions coerce to booleans.
  • Use === to avoid coercion surprises.