Sub topic 2
What Type Coercion Is: Explicit and Implicit Conversion
This chapter assumes you know the eight JavaScript types and how primitives differ from objects. Type coercion means converting a value from one type to another. Coercion is explicit when you call Number(), String(), or Boolean() yourself. It is implicit when an operator such as +, -, or if converts the value for you. Both kinds follow the same internal rules: ToBoolean, ToNumber, ToString, and ToPrimitive.
Truthy and Falsy Values
ToBoolean has a short list of falsy values: false, 0, -0, 0n, "", null, undefined, and NaN. Every other value is truthy. That includes "0", [], and {}.
Converting to Numbers and Strings
ToNumber trims whitespace from strings and turns "" into 0. Any other non-numeric text becomes NaN. null becomes 0 and undefined becomes NaN. ToString turns arrays into comma-joined text and plain objects into "[object Object]".
console.log(Number(""), Number(" 42 "), Number("42px")); // 0 42 NaN
console.log(Number(null), Number(undefined), Number([5])); // 0 NaN 5
console.log(String([1, 2]), String({})); // "1,2" "[object Object]"
console.log(Boolean("0"), Boolean([]), Boolean(0n)); // true true falseHow Objects Become Primitives
Before an object can become a number or a string, ToPrimitive converts it to a primitive. The conversion receives a hint: "number", "string", or "default". JavaScript calls Symbol.toPrimitive if the object defines it. Otherwise the number and default hints try valueOf first, and the string hint tries toString first.
const price = {
valueOf() { return 9.99; },
toString() { return "$9.99"; }
};
console.log(price * 2); // 19.98
console.log(`${price}`); // "$9.99"
console.log(price + ""); // "9.99"Coercion in + and Other Arithmetic Operators
The + operator first converts both operands to primitives. If either one is a string, + concatenates. Otherwise it adds numbers. The operators -, *, and / always convert their operands to numbers.
console.log(1 + "2", "3" - 1, true + 1); // "12" 2 2
console.log([] + [], [] + {}); // "" "[object Object]"
console.log(1 + undefined); // NaNExercise
What does [2] * "3" + [1] evaluate to, and why?
Show answer
"61". [2] becomes "2" and then 2, and "3" becomes 3, so the multiplication gives 6. Then [1] becomes the string "1", so + concatenates 6 and "1" into "61".