Sub topic 2
Escaping Backticks and Dollar-Brace Sequences
This chapter assumes you already know basic template literal syntax and ${} interpolation. It also uses array methods such as map and join, plus objects that define methods.
Escaping Backticks and `${`
Inside a template literal, two sequences have special meaning. A backtick ends the literal, and ${ starts a substitution. If you want either one to appear as plain text, put a backslash in front of it.
console.log(`Use \`backticks\` and \${not interpolated}`);
// Use `backticks` and ${not interpolated}A $ on its own, or a { on its own, needs no escape. Only the two-character sequence ${ starts a substitution. That means ` Price: $5 ` works as written.
How Interpolated Values Become Strings
Each substitution is evaluated and then converted with string conversion, the same rule String(value) follows. For objects, string conversion calls toString first. The + operator is different: it converts objects with the "default" hint, and for ordinary objects that calls valueOf first.
const obj = {
toString() { return "str"; },
valueOf() { return 42; }
};
console.log(`${obj}`); // str
console.log("" + obj); // 42
console.log(`${[1, 2]}`); // 1,2
console.log(`${null}`); // null| Value | `${value}` result |
|---|---|
| `null` | `"null"` |
| `undefined` | `"undefined"` |
| `[1, 2]` | `"1,2"` |
| `{}` | `"[object Object]"` |
| `Symbol("s")` | throws `TypeError` |
A common mistake is interpolating a plain object and getting [object Object]. Use JSON.stringify(value) when you want to see its contents. A Symbol cannot be converted implicitly, so call String(sym) or read sym.description instead.
Nesting Template Literals
A substitution can hold any expression, and that includes another template literal. Nesting is handy for building repeated structure:
const items = ["a", "b"];
const list = `<ul>${items.map(item => `<li>${item}</li>`).join("")}</ul>`;
console.log(list); // <ul><li>a</li><li>b</li></ul>Remember to call .join(""). If you leave it out, the array is converted with its default toString, and commas appear between the items: <li>a</li>,<li>b</li>.
Exercise
What does this print, and why? const d = { toString() { return "D"; }, valueOf() { return 7; } }; console.log(${d} + d);
Show answer
It prints "D7". The template literal uses string conversion, which calls toString and gives "D". The + operator then converts d with the default hint, which calls valueOf and gives 7, and that number is concatenated onto the string.
Exercise
Write a template literal that outputs the text: Cost: ${price} in USD
Show answer
Cost: \${price} in \USD\``