Sub topic 4
Template Literals and Interpolation
This chapter assumes you know basic JavaScript syntax, can run code in a browser console or Node.js, and have read the earlier chapters on string literals and immutability. A template literal is a string written between backticks (` ``) instead of quotes. It can contain embedded expressions and can span several lines without escape sequences.
The Working Model
Inside a template literal, ${expression} marks a placeholder. JavaScript evaluates each placeholder from left to right, converts each result to a string, and joins those results with the literal text around them. The result is an ordinary string primitive.
const user = { name: "Ada", items: 3 };
const msg = `${user.name} has ${user.items} item${user.items === 1 ? "" : "s"}`;
console.log(msg); // Ada has 3 items
console.log(`2 + 3 = ${2 + 3}`); // 2 + 3 = 5
console.log(`Upper: ${user.name.toUpperCase()}`); // Upper: ADAA placeholder accepts any expression, including function calls, ternaries, and nested template literals. It does not accept statements such as if or for.
Multi-line Strings
Line breaks inside backticks become part of the string, and so does indentation.
const item = "Milk";
const html = `<ul>
<li>${item}</li>
</ul>`;
console.log(html);
// <ul>
// <li>Milk</li>
// </ul>Escaping Backticks and Placeholders
To get a literal backtick, write ` \ `. To get a literal ${, escape the dollar sign. Normal escapes such as \n and \t` work the same way they do in quoted strings.
const x = 10;
console.log(`Use \` for templates and \${x} for placeholders`);
// Use ` for templates and ${x} for placeholders
console.log(`x is ${x}\tdone`); // x is 10 doneHow Values Are Converted
Placeholders convert values with the string conversion rules, the same rules String(value) uses. This produces some results that catch people out:
| Value in `${}` | Result |
|---|---|
| `null` | `"null"` |
| `undefined` | `"undefined"` |
| `[1, 2]` | `"1,2"` |
| `{ a: 1 }` | `"[object Object]"` |
| `Symbol("s")` | throws `TypeError` |
The + operator converts values in a different way. It tries valueOf first, and a template literal calls toString first:
const obj = {
valueOf() { return 1; },
toString() { return "two"; },
};
console.log("" + obj); // 1
console.log(`${obj}`); // twoCommon Errors
- Using quotes instead of backticks.
"Hi ${name}"prints the placeholder text exactly as written. Only backticks interpolate. - Interpolating objects. You get
[object Object]. UseJSON.stringify(obj)or pick out the properties you need. - Inserting untrusted input into HTML or SQL. Interpolation does no escaping at all. Escape the values yourself or use a parameterized API.
- Unexpected whitespace in multi-line templates, as described above.
Exercise
What does this code log, and why? const n = 0; const a = [1, 2]; console.log(${n || "none"} | ${a} | ${"${n}"});
Show answer
It logs "none | 1,2 | ${n}". The expression n || "none" evaluates to "none" because 0 is falsy. The array is converted with toString, which joins its elements with commas. The last placeholder evaluates the ordinary double-quoted string "${n}", and double quotes never interpolate, so those characters appear as written.
Exercise
Rewrite "Total: " + qty + " x $" + price + " = $" + qty * price as a template literal.
Show answer
Total: ${qty} x $${price} = $${qty * price}. A dollar sign that is not directly followed by { is literal text, so $${price} prints a dollar sign followed by the price.