Sub topic 5
How Interpolated Values Become Strings
A template literal always produces a string, but the values you put inside ${} can be numbers, arrays, objects, symbols, or anything else. Each value goes through a specific conversion step before it is joined into the result. Most of the time the output is what you expect. Sometimes it is not. You might see [object Object] in a log line, or a TypeError that only appears when a symbol reaches the template, or an object that prints differently in a template than with +.
This chapter assumes you know JavaScript variables, expressions and functions, regular quoted strings, arrays with map, join and reduce, and the basic ${} syntax covered earlier. It also assumes you have seen object methods such as toString.
The Rule: Every Substitution Goes Through ToString
The language specification defines template evaluation in a few steps. JavaScript evaluates each expression in ${}, passes the result to the internal ToString operation, and concatenates the pieces with the literal text around them. ToString is the same operation that String(value) uses for most inputs, with one notable exception covered below.
For primitive values, ToString follows fixed rules:
| Value type | Example | Result |
|---|---|---|
| String | `${"hi"}` | `hi` (unchanged) |
| Number | `${3.5}` | `3.5` |
| BigInt | `${10n}` | `10` (no `n` suffix) |
| Boolean | `${true}` | `true` |
| null | `${null}` | `null` |
| undefined | `${undefined}` | `undefined` |
| Symbol | `${Symbol("id")}` | throws `TypeError` |
console.log(`${42}`); // 42
console.log(`${-0}`); // 0
console.log(`${1e21}`); // 1e+21
console.log(`${0.1 + 0.2}`); // 0.30000000000000004
console.log(`${NaN}`); // NaN
console.log(`${10n}`); // 10
console.log(`${true}`); // true
console.log(`${null}`); // null
console.log(`${undefined}`); // undefinedSome of these results surprise people. Negative zero prints as 0. Very large numbers switch to exponent notation at 1e21. Floating-point rounding errors appear in full. null and undefined print as words, which is how strings like Hello, undefined! reach production when a variable was never set.
Objects: ToPrimitive with the "string" Hint
When the value is an object, ToString first converts it to a primitive with an internal operation called ToPrimitive, passing a hint of "string". The hint tells the object which kind of primitive the caller would like. The steps are:
- If the object has a
Symbol.toPrimitivemethod, call it with"string". If it returns a primitive, use that primitive. If it returns an object, throw aTypeError. - Otherwise, call
toString(). If it exists and returns a primitive, use it. - Otherwise, call
valueOf(). If it exists and returns a primitive, use it. - If neither produced a primitive, throw a
TypeError.
The primitive is then converted with the primitive rules from the table above.
Because toString comes first, most objects rely on the toString they inherit. That is why the common cases look like this:
console.log(`${[1, 2, 3]}`); // 1,2,3
console.log(`${[1, [2, [3]]]}`); // 1,2,3
console.log(`${[null, undefined, 0]}`); // ,,0
console.log(`[${[]}]`); // []
console.log(`${{ a: 1 }}`); // [object Object]
console.log(`${new Date(0).getTime()}`); // 0
console.log(`${/ab+c/g}`); // /ab+c/g
console.log(`${new Error("boom")}`); // Error: boom
console.log(`${function f() { return 1; }}`); // function f() { return 1; }Array.prototype.toString calls join(","). join flattens nested arrays because each inner array is converted the same way. It also turns null and undefined elements into empty strings, so [null, undefined, 0] becomes ,,0. An empty array becomes an empty string. Plain objects inherit Object.prototype.toString, which returns [object Object]. Functions print their source text.
The fallback to valueOf
The fallback in steps 2 and 3 only matters when toString is missing or returns a non-primitive. It is rare in practice, but it explains some odd behavior:
const odd = {
toString() { return {}; },
valueOf() { return "from valueOf"; }
};
console.log(`${odd}`); // from valueOf
const bare = Object.create(null);
try {
console.log(`${bare}`);
} catch (e) {
console.log(e.constructor.name); // TypeError
}Object.create(null) produces an object with no prototype, so it has neither toString nor valueOf. Libraries sometimes use such objects as dictionaries. If you interpolate one by mistake, it throws instead of printing [object Object].
Template vs + Concatenation
The + operator also produces strings, but it converts objects differently. + calls ToPrimitive with the hint "default". For ordinary objects, the default hint tries valueOf before toString. Interpolation tries toString 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)); // strYou can watch the hints directly with Symbol.toPrimitive, which receives the hint as its argument:
const probe = {
[Symbol.toPrimitive](hint) {
console.log("hint:", hint);
return hint === "number" ? 1 : "text";
}
};
const a = `${probe}`; // hint: string
const b = probe + ""; // hint: default
const c = +probe; // hint: number
console.log(a, b, c); // text text 1Date objects are the main built-in exception. Their Symbol.toPrimitive method treats "default" like "string", so date + "" and ` ${date} give the same readable date. Subtraction uses the "number"` hint and gives the timestamp:
const d = new Date(0);
console.log(`${d}` === String(d)); // true
console.log(d + "" === String(d)); // true
console.log(d - 0); // 0The difference is easy to miss because it only shows up with objects whose valueOf returns a primitive. Built-in examples are Number, Boolean and String wrapper objects, plus your own classes that define valueOf. A Money class whose valueOf returns cents and whose toString returns "$12.50" prints $12.50 in a template and 1250 after "" + money.
The table compares the common ways to turn a value into a string:
| Operation | Hint for objects | Symbol | Notes |
|---|---|---|---|
| `` `${v}` `` | string | TypeError | toString first |
| `String(v)` | string | `"Symbol(desc)"` | only form that accepts symbols |
| `"" + v` | default | TypeError | valueOf first for ordinary objects |
| `"".concat(v)` | string | TypeError | same as template |
| `[v].join("")` | string | TypeError | `null`/`undefined` become `""` |
Symbols Throw
A symbol cannot be converted with ToString. The language blocks this on purpose so that a symbol used as a property key is not silently turned into a string key. String(symbol) is a special case that returns a description such as Symbol(id). Interpolation does not get that special case:
const s = Symbol("id");
try {
console.log(`${s}`);
} catch (e) {
console.log(e instanceof TypeError); // true
}
console.log(String(s)); // Symbol(id)
console.log(`${s.description}`); // id
console.log(`${String(s)}`); // Symbol(id)This matters in generic code such as logging helpers that interpolate whatever they receive. If any value could be a symbol, wrap it in String(value) before interpolating.
Conversion Happens During Evaluation, in Order
JavaScript does not evaluate all substitutions first and convert them afterward. It evaluates the first expression, converts it, then moves to the second, and so on from left to right:
const log = [];
const first = { toString() { log.push("convert first"); return "A"; } };
const second = { toString() { log.push("convert second"); return "B"; } };
const result = `${(log.push("eval first"), first)}-${(log.push("eval second"), second)}`;
console.log(result); // A-B
console.log(log);
// [ 'eval first', 'convert first', 'eval second', 'convert second' ]As a result, if one value's toString throws, the later expressions never run. If a toString method has side effects, they happen in source order between the expressions. You rarely depend on this, but it helps when you debug a template whose later expression seems to be skipped.
When Default Conversion Is the Wrong Choice
Default conversion is built for correctness, not presentation. In real output you usually want to format values yourself before they reach ${}:
const price = 0.1 + 0.2;
const tags = ["js", "strings"];
const config = { retries: 3, verbose: false };
const total = 1234567.891;
console.log(`Price: ${price.toFixed(2)}`); // Price: 0.30
console.log(`Tags: ${tags.join(", ")}`); // Tags: js, strings
console.log(`Config: ${JSON.stringify(config)}`); // Config: {"retries":3,"verbose":false}
console.log(`Total: ${total.toLocaleString("en-US", { maximumFractionDigits: 2 })}`);
// Total: 1,234,567.89For your own classes, define toString to control how instances print in templates. Define Symbol.toPrimitive only if you need different results for each hint:
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
toString() {
return `(${this.x}, ${this.y})`;
}
}
console.log(`Start at ${new Point(2, 3)}`); // Start at (2, 3)Tagged Templates Skip This Step
Everything in this chapter applies to untagged template literals. When a template has a tag function in front of it, which a later chapter covers, the evaluated values go to the tag function unchanged. No ToString call happens. The tag can then inspect types, escape strings, or keep objects as objects. A tag that wants the standard behavior has to call String(value) itself, and it gets to choose how symbols and null are handled.
Common Errors at a Glance
| Symptom | Cause | Fix |
|---|---|---|
| `undefined` or `null` in output | Missing value converted to a word | `${v ?? "default"}` |
| `[object Object]` | Plain object's inherited `toString` | `JSON.stringify` or a custom `toString` |
| `1,2,3` with no spaces | Array `toString` uses `join(",")` | `arr.join(", ")` |
| `0.30000000000000004` | Full float precision | `toFixed`, `Intl.NumberFormat` |
| `TypeError: Cannot convert a Symbol value to a string` | Symbol in `${}` | `String(sym)` or `sym.description` |
| `TypeError: Cannot convert object to primitive value` | Null-prototype object, or no method returned a primitive | Convert explicitly first |
| Template and `+` disagree | Different hints: string vs default | Pick one form, or align `valueOf` and `toString` |
Exercise
Predict the output of each line: ${[[], [null], [1, [2]]]}, ${{}}, and ${[{}]}.
Show answer
The first line prints ",,1,2". The outer array joins three elements with commas. The empty array becomes "", [null] becomes "" because join turns null into an empty string, and [1, [2]] becomes "1,2". The second line prints "[object Object]". The third line also prints "[object Object]", because the array joins its single element and that element converts with Object.prototype.toString.
Exercise
A class Temperature has valueOf() returning the number 21 and toString() returning "21°C". What do ${t}, "Now: " + t, and t + 1 produce, and why?
Show answer
${t} gives "21°C" because interpolation uses the string hint, which tries toString first. "Now: " + t gives "Now: 21" because + uses the default hint, which tries valueOf first for ordinary objects, and then the number 21 is concatenated. t + 1 gives the number 22: valueOf returns 21, neither operand is a string, so + performs numeric addition.
Exercise
A logging helper is written as const fmt = (v) => value=${v};. Name two inputs that make it throw, and rewrite it so it never throws on those inputs.
Show answer
Symbol("x") throws because symbols cannot be converted by ToString. Object.create(null) throws because it has no toString or valueOf. A safe version: const fmt = (v) => { if (typeof v === "symbol") return value=${String(v)}; try { return value=${v}; } catch { return "value=[unprintable]"; } };. The typeof check handles symbols. The try/catch handles objects whose conversion fails.