JavaScriptMedium
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 byString(x). - To number: triggered by
-,*,/,%, unary+, comparisons like<, and loose==with numbers.Number("")is0,Number(" 42 ")is42,Number("4x")isNaN,Number(null)is0,Number(undefined)isNaN. - To boolean: triggered by
if,&&,||,!, andBoolean(x). Only the falsy values becomefalse.
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 withNumber.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// Implicit2console.log(1 + "2"); // "12" (+ with a string concatenates)3console.log("3" - 1); // 2 (- always converts to numbers)4console.log("5" * "2"); // 105console.log(true + 1); // 26console.log([] + []); // ""7console.log([] + {}); // "[object Object]"8console.log("10" < "9"); // true (string comparison, char by char)9console.log(10 < "9"); // false (number comparison)1011// Explicit12console.log(Number(""), Number(" 42 "), Number("4x"), Number(null), Number(undefined)); // 0 42 NaN 0 NaN13console.log(String(123), String(null), String([1, 2])); // "123" "null" "1,2"14console.log(Boolean("0"), Boolean(0), Boolean([]), Boolean("")); // true false true false1516// A classic bug with form values (always strings)17const qtyInput = "2";18console.log(qtyInput + 1); // "21"19console.log(Number(qtyInput) + 1); // 32021// Control conversion with Symbol.toPrimitive22const 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.