Sub topic 8
What Type Coercion Is: Explicit and Implicit Conversion
This chapter assumes you know basic JavaScript syntax, can work with objects and arrays, and can run code in a browser console or Node.js. It also builds on the earlier chapters about the eight types, so terms like primitive, wrapper object, and NaN are used without being defined again.
Type coercion is the conversion of a value from one type to another. JavaScript converts values all the time, sometimes because you asked it to and sometimes because an operator or statement needed a different type than the one you gave it. This chapter covers the overall model: the two ways conversion happens, the small set of internal rules behind every conversion, and the places in the language where those rules run. Later chapters go through each rule in detail.
Explicit Conversion: You Ask for It
Explicit conversion means your code names the target type. The usual tools are the Number, String, and Boolean functions called without new, plus parsing functions such as parseInt and parseFloat.
console.log(Number("42")); // 42
console.log(String(42)); // "42"
console.log(Boolean("")); // false
console.log(parseInt("42px", 10)); // 42
console.log(Number("42px")); // NaNWhen you call these functions without new, they return primitives. Calling them with new creates wrapper objects, which is almost never what you want:
const wrapped = new Boolean(false);
console.log(typeof wrapped); // "object"
if (wrapped) {
console.log("runs: every object is truthy, even a wrapped false");
}Explicit conversion is easy to read. Someone looking at Number(input) knows a number is expected at that point.
Implicit Conversion: The Language Does It for You
Implicit conversion happens when an operator or statement needs a particular type and silently converts what it receives. Nothing in the code says "convert here".
console.log("5" * 2); // 10: * needs numbers
console.log("5" + 2); // "52": + saw a string and concatenated
console.log(`${7} days`); // "7 days": template literals need strings
console.log("1" == 1); // true: == converted "1" to 1
if ("hello") {
console.log("a non-empty string counts as true in a condition");
}Implicit coercion isn't a bug in the language. It is defined precisely in the ECMAScript specification, and every result above follows from fixed rules. The trouble is that the rules aren't visible at the call site, so readers have to know them to predict the result.
The Abstract Operations Behind Every Conversion
The specification defines conversion through internal algorithms called abstract operations. You cannot call them by name from JavaScript, but explicit and implicit conversions both run them. Four of them cover nearly everything:
| Abstract operation | Produces | Used by, for example |
|---|---|---|
| ToBoolean | `true` or `false` | `if`, `while`, `!`, `Boolean(x)` |
| ToNumber (part of ToNumeric) | a number | `-`, `*`, `/`, unary `+`, `Number(x)` |
| ToString | a string | template literals, `String(x)`, property keys |
| ToPrimitive | a primitive | any of the above when the input is an object |
ToPrimitive is the bridge for objects. Before an object can become a number or a string, the engine first reduces it to a primitive by calling Symbol.toPrimitive, valueOf, or toString, then applies ToNumber or ToString to that primitive. ToBoolean is the exception: it never calls ToPrimitive, because every object is simply truthy.
If you know which abstract operation a piece of syntax triggers, you can predict its result. The rest of this tutorial is about learning that mapping.
Where Implicit Coercion Happens
These are the places where JavaScript converts values for you:
| Context | Operation triggered | Column | Column |
|---|---|---|---|
| Conditions in `if`, `while`, `for`, `? :`, and the operand of `!` | ToBoolean | ||
| Left operand of `\ | \ | `, `&&` | ToBoolean, but the original operand value is returned |
| `-`, `*`, `/`, `%`, `**`, unary `+` and `-` | ToPrimitive, then ToNumeric | ||
| Binary `+` | ToPrimitive on both sides, then ToString if either is a string, otherwise ToNumeric | ||
| Template literal `${x}` | ToString | ||
| `==` and `!=` with different types | A mix of ToPrimitive and ToNumber | ||
| `<`, `>`, `<=`, `>=` | ToPrimitive, then string or numeric comparison | ||
| Property access `obj[key]` | ToPropertyKey (ToString unless the key is a symbol) |
The last row is easy to miss:
const scores = {};
scores[1] = "first";
scores[{}] = "object key";
console.log(Object.keys(scores)); // [ '1', '[object Object]' ]
console.log(scores["1"]); // "first": the number 1 became the string "1"Explicit and Implicit Are Not Always Equivalent
It is tempting to treat +x as shorthand for Number(x) and x + "" as shorthand for String(x). They usually agree, but they don't in these cases:
const id = Symbol("id");
console.log(String(id)); // "Symbol(id)"
// console.log(`${id}`); // TypeError: Cannot convert a Symbol value to a string
// console.log(id + ""); // TypeError
console.log(Number(10n)); // 10
// console.log(+10n); // TypeError: Cannot convert a BigInt value to a number
const price = {
valueOf() { return 9.99; },
toString() { return "$9.99"; }
};
console.log(String(price)); // "$9.99": asks for a string first
console.log(price + ""); // "9.99": + asks with the "default" hint, which uses valueOf firstThe functions String and Number include special handling for symbols and BigInts. The operators don't. With objects, String(x) and x + "" pass different hints to ToPrimitive, so they can call different methods. The "How Objects Become Primitives" chapter explains hints in full.
A Common Real-World Error
Values that come from outside the program are usually strings. These include form fields, URL parameters, localStorage, and command-line arguments. Mixing them with numbers through + is a frequent source of bugs:
const quantityFromForm = "3"; // input.value is always a string
const bonus = 2;
console.log(quantityFromForm + bonus); // "32": concatenation
console.log(Number(quantityFromForm) + bonus); // 5: intended result
const raw = "abc";
const parsed = Number(raw);
if (Number.isNaN(parsed)) {
console.log("invalid quantity");
}The fix is to convert explicitly at the boundary where data enters the program, check that the result is valid, and work only with correctly typed values after that point.
Exercise
For each expression, name whether the conversion is explicit or implicit and which abstract operation runs first: (a) Boolean([]), (b) "6" / "2", (c) obj[true], (d) ` ${[1, 2]} `.
Show answer
(a) Explicit, ToBoolean, giving true because every object is truthy. (b) Implicit, ToPrimitive then ToNumber on both operands, giving 3. (c) Implicit, ToPropertyKey, which runs ToString and reads the property "true". (d) Implicit, ToString; because the array is an object, ToPrimitive runs first and calls toString, giving "1,2".
Exercise
A function receives count that may be a string from a form. Why can count + 1 and Number(count) + 1 give different results, and why can +count and Number(count) differ?
Show answer
If count is a string, count + 1 concatenates (for example "41"), while Number(count) + 1 adds numerically (42). +count and Number(count) match for strings, but unary + throws a TypeError for a BigInt, whereas Number converts it.