Hiprup

What is type coercion in JavaScript?

Type coercion is JavaScript automatically converting a value from one type to another when an operation expects a certain type.

  • Implicit — happens automatically, e.g. "5" + 1 gives "51", while 5 - "1" gives 4.

  • Explicit — you convert on purpose using Number(), String() or Boolean().

  • Truthy / falsy — values coerce to true or false in boolean contexts. The falsy values are false, 0, "", null, undefined and NaN.

Watch out: + concatenates if either side is a string, while -, * and / always force numbers.

// Implicit coercion
console.log('5' + 3);      // '53' (number -> string)
console.log('5' - 3);      // 2 (string -> number)
console.log('5' * '3');    // 15 (both -> number)
console.log(true + 1);     // 2 (true -> 1)
console.log(false + 1);    // 1 (false -> 0)
console.log('' + 1);       // '1' (number -> string)
console.log(null + 1);     // 1 (null -> 0)
console.log(undefined + 1); // NaN (undefined -> NaN)

// Falsy values (memorize these 6)
console.log(Boolean(false));     // false
console.log(Boolean(0));         // false
console.log(Boolean(''));        // false
console.log(Boolean(null));      // false
console.log(Boolean(undefined)); // false
console.log(Boolean(NaN));       // false

// Truthy surprises
console.log(Boolean([]));        // true! (empty array)
console.log(Boolean({}));        // true! (empty object)
console.log(Boolean('0'));       // true! (non-empty string)
console.log(Boolean('false'));   // true! (non-empty string)

// Explicit coercion
console.log(Number('42'));       // 42
console.log(Number(''));         // 0
console.log(Number('abc'));      // NaN
console.log(parseInt('42px'));   // 42 (stops at non-digit)
console.log(+'42');              // 42 (unary + converts to number)
  • with any string concatenates (string wins). Other arithmetic operators convert to numbers. The 6 falsy values must be memorized. [] and {} are truthy (common gotcha). Unary + is the shortest number conversion. parseInt stops at the first non-digit character.

Memorize the 6 falsy values. Know that [] and {} are truthy.

The + operator behavior (string concatenation vs addition) is the most commonly tested. '5' + 3 = '53' but '5' - 3 = 2 is the classic question.

What is type coercion in JavaScript? | Hiprup