FundamentalsChapter 18 of 21
Type Coercion
When JavaScript converts types for you, and how to take the wheel.
Conversion you did not ask for
When an operator gets types it did not expect, JavaScript converts rather than complains. Knowing the rules turns baffling results into predictable ones.
JavaScript
console.log('5' + 3);
console.log('5' - 3);
console.log('5' * '2');
console.log(1 + true);Output
53 2 10 2
The + operator is the odd one out: if either side is a string it joins them as text. Every other arithmetic operator converts to numbers first, which is why subtraction on strings does arithmetic.
The one to watch
JavaScript
const input = '10';
console.log(input + 1);
console.log(Number(input) + 1);Output
101 11
Gotcha
Values from form fields, URLs and JSON.parse of text are strings. Adding one to a total without converting first is a classic bug, and it produces a plausible-looking wrong answer rather than an error.
Converting on purpose
JavaScript
console.log(Number('42'), Number(''), Number('abc'));
console.log(parseInt('42px', 10), parseFloat('3.5rem'));
console.log(String(42), (42).toString());
console.log(Boolean(''), Boolean('no'));Output
42 0 NaN 42 3.5 42 42 false true
Numberis strict: the whole string must be a number, or you getNaN.parseIntandparseFloatare lenient: they read as far as they can and stop.- Always pass the radix to
parseInt, soparseInt(value, 10), or unusual input can be read as another base.
Objects converting to primitives
When an object meets an operator that wants a primitive, it is converted, and the results are famously strange.
JavaScript
console.log([] + []);
console.log([1, 2] + [3]);
console.log({} + '');
console.log([10] * 2);Output
1,23 [object Object] 20
Arrays convert by joining with commas, plain objects convert to [object Object]. None of this is useful in real code; it is worth seeing once so it is never mysterious.
The habit
Convert deliberately at the edges, where data arrives, and then work with values whose types you know. That single habit removes most coercion surprises.
Test yourself
2 questionsWhy does '5' + 3 give '53' but '5' - 3 gives 2?
Show the answer
+ joins text when either side is a string; other operators convert to numbers + is the only arithmetic operator with a string meaning, which is why it behaves differently.
What does Number("") return?
Show the answer
0 An empty string converts to 0, which is a common source of a wrong total when a field is left blank.
Truthy and Falsy
The eight falsy values, and why the list is worth memorising.