What is type coercion in JavaScript

· Category: JavaScript

Short answer

Type coercion is the automatic or implicit conversion of values from one data type to another during operations like comparison or concatenation.

How it works

JavaScript performs coercion in two flavors:

  • Implicit coercion: 5 + '5' becomes '55' because the number is converted to a string.
  • Explicit coercion: Number('5') or String(5) manually convert values.

Equality operators behave differently:

  • == triggers coercion (0 == '0' is true).
  • === does not trigger coercion (0 === '0' is false).

Falsy values like 0, '', null, undefined, NaN, and false convert to false in boolean contexts.

Example

console.log([] + {});   // '[object Object]'
console.log({} + []);   // 0 (in some engines)
console.log(!!'hello'); // true

Why it matters

Relying on implicit coercion leads to subtle bugs. Prefer === and explicit conversions to make intent clear and improve reliability.