What is type coercion?

Type coercion is JavaScript automatically converting a value from one type to another, either implicitly (when operators or comparisons need a different type) or explicitly (when you call Number(), String() or Boolean()).

The three conversions

  • To string: triggered by + when either side is a string, by template literals, and by String(x).
  • To number: triggered by -, *, /, %, unary +, comparisons like <, and loose == with numbers. Number("") is 0, Number(" 42 ") is 42, Number("4x") is NaN, Number(null) is 0, Number(undefined) is NaN.
  • To boolean: triggered by if, &&, ||, !, and Boolean(x). Only the falsy values become false.

The + operator is special

If either operand is a string after conversion to a primitive, + concatenates. Otherwise it adds. That is why 1 + "2" is "12" but "3" - 1 is 2.

Objects

Objects are first converted to primitives with Symbol.toPrimitive, then valueOf, then toString. [] + [] is "", [] + {} is "[object Object]".

Best practices

  • Convert explicitly at boundaries: form inputs and URL params are strings, so call Number(value) and validate with Number.isFinite.
  • Use === to avoid coercion in comparisons.
  • Be careful with + when values might be strings.
  • TypeScript catches most accidental coercion at compile time.

Code example

js
1// Implicit
2console.log(1 + "2"); // "12" (+ with a string concatenates)
3console.log("3" - 1); // 2 (- always converts to numbers)
4console.log("5" * "2"); // 10
5console.log(true + 1); // 2
6console.log([] + []); // ""
7console.log([] + {}); // "[object Object]"
8console.log("10" < "9"); // true (string comparison, char by char)
9console.log(10 < "9"); // false (number comparison)
10
11// Explicit
12console.log(Number(""), Number(" 42 "), Number("4x"), Number(null), Number(undefined)); // 0 42 NaN 0 NaN
13console.log(String(123), String(null), String([1, 2])); // "123" "null" "1,2"
14console.log(Boolean("0"), Boolean(0), Boolean([]), Boolean("")); // true false true false
15
16// A classic bug with form values (always strings)
17const qtyInput = "2";
18console.log(qtyInput + 1); // "21"
19console.log(Number(qtyInput) + 1); // 3
20
21// Control conversion with Symbol.toPrimitive
22const price = { [Symbol.toPrimitive]: (hint) => (hint === "number" ? 9.99 : "$9.99") };
23console.log(+price, `${price}`); // 9.99 "$9.99"

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app