Sub topic 5
How Interpolated Values Become Strings
This chapter assumes you can write template literals with ${} substitutions. It also assumes you know what objects, arrays, and methods are in JavaScript. The question here is what happens after a substitution's expression is evaluated, because the result has to become text before it can be inserted.
The rule: string conversion
Every value placed in a substitution goes through the language's string conversion, the same abstract operation that String(value) performs. The one exception is Symbol, which is covered below. Primitives convert in predictable ways:
console.log(`${42}`); // 42
console.log(`${-0}`); // 0
console.log(`${10n}`); // 10
console.log(`${true}`); // true
console.log(`${null}`); // null
console.log(`${undefined}`); // undefinedNote that null and undefined are not dropped. They appear as the words null and undefined. That causes a common bug: a missing field shows up in the UI as "Hello, undefined".
Objects go through ToPrimitive with a "string" hint
An object is first turned into a primitive. With the string hint, JavaScript calls the object's toString() method. Only if that does not return a primitive does it try valueOf(). Then it converts the resulting primitive to a string.
console.log(`${[1, [2, 3]]}`); // 1,2,3
console.log(`${[]}`); // (empty string)
console.log(`${[null, undefined]}`); // ,
console.log(`${{}}`); // [object Object]
console.log(`${new Date(0)}`.startsWith("Thu Jan 01 1970")); // trueArrays use Array.prototype.toString, which calls join(","). That method flattens nested arrays and writes null and undefined elements as empty strings. Plain objects inherit Object.prototype.toString, which returns [object Object].
Where `+` concatenation differs
The + operator also converts objects to primitives, but it uses the "default" hint. For ordinary objects, the default hint tries valueOf() first. An object that defines both methods can therefore give different results:
const obj = {
toString() { return "str"; },
valueOf() { return 42; }
};
console.log(`${obj}`); // str
console.log("" + obj); // 42
console.log(String(obj)); // str
console.log("".concat(obj)); // strYou can watch the hint directly with Symbol.toPrimitive:
const probe = {
[Symbol.toPrimitive](hint) {
return hint;
}
};
console.log(`${probe}`); // string
console.log("" + probe); // defaultDate objects are a special case. Their Symbol.toPrimitive treats the "default" hint as "string", so "" + date and ` ${date} ` produce the same text.
| Technique | Hint for objects | Method tried first | Symbol value |
|---|---|---|---|
| `` `${x}` `` | string | `toString` | throws TypeError |
| `String(x)` | string | `toString` | returns `"Symbol(desc)"` |
| `"" + x` | default | `valueOf` | throws TypeError |
| `"".concat(x)` | string | `toString` | throws TypeError |
Symbols throw
Implicit string conversion of a Symbol throws, and template literals are no exception:
const id = Symbol("id");
try {
console.log(`${id}`);
} catch (e) {
console.log(e instanceof TypeError); // true
}
console.log(`${String(id)}`); // Symbol(id)
console.log(`${id.description}`); // idCommon errors and fixes
[object Object]in output. You interpolated a plain object. UseJSON.stringify(obj), pick specific properties, or give the class its owntoString().- "undefined" or "null" in text. Supply a fallback: `
Hello, ${name ?? "guest"}`. - Unexpected commas. An array was joined with
,. Calljoinyourself with the separator you want: `${tags.join(" | ")}`. - Different output from
+and from a template. The object definesvalueOf. Choose one style, or defineSymbol.toPrimitiveso the result is explicit.
class Money {
constructor(cents) { this.cents = cents; }
toString() { return `$${(this.cents / 100).toFixed(2)}`; }
}
console.log(`Total: ${new Money(1999)}`); // Total: $19.99In ` $${...} , the first $ is plain text because a substitution only starts at the ${` sequence.
Exercise
Predict the output of each line: (1) ${[1, null, 3]} (2) ${{ toString: () => "A", valueOf: () => "B" }} (3) "" + { toString: () => "A", valueOf: () => "B" } (4) ${[[], [[]]]}
Show answer
(1) "1,,3" because join writes null as an empty string. (2) "A" because the string hint calls toString first. (3) "B" because + uses the default hint, and ordinary objects then try valueOf first. (4) "," because both inner arrays become empty strings and are joined with one comma.
Exercise
A logger writes User: ${user} and prints "User: [object Object]". Give two ways to get readable output, and say which one also changes what "" + user prints.
Show answer
Use ${JSON.stringify(user)} at the call site, or define a toString() method on the user object or its class. Defining toString also changes "" + user, as long as the object has no custom valueOf, because the default valueOf returns the object itself and conversion then falls back to toString. JSON.stringify only affects the call site where you use it.