Sub topic 6
Nesting Template Literals
This chapter assumes you can already write template literals with ${} substitutions, that you know how interpolated values are converted to strings, and that you are comfortable with map, join, arrow functions, and the conditional (ternary) operator.
A substitution, the part inside ${...}, can hold any JavaScript expression. A template literal is itself an expression, so you can put one template literal inside the substitution of another. This is called nesting. It is the usual way to build structured text such as HTML lists, tables, or messages that change shape depending on data.
The Basic Idea
Here is the smallest useful case: one template literal whose substitution contains a second one.
const user = { name: "Ada", admin: true };
const greeting = `Hello, ${user.admin ? `admin ${user.name}` : user.name}!`;
console.log(greeting); // Hello, admin Ada!The outer template is ` Hello, ${...}! . Inside its substitution, the ternary picks between the inner template admin ${user.name} and the plain value user.name. The inner template is evaluated first and produces the string "admin Ada"`. The outer template then inserts that string just as it would insert any other value.
Nothing about the inner template is special. It is an ordinary expression that happens to be written with backticks.
How the Parser Tells the Levels Apart
The opening backtick of the inner template does not end the outer one, so it is worth seeing why. The JavaScript lexer reads a template literal in two modes:
- Template text mode. Characters are literal text. A backtick ends the template, and
${starts a substitution. - Expression mode. After
${, the lexer reads normal JavaScript tokens: identifiers, operators, string literals, object literals, and also new template literals. The substitution ends at the}that matches the${.
When the lexer meets a backtick in expression mode, it starts a new template literal, one level deeper. That inner template has its own text mode and its own substitutions. When it closes, the lexer returns to expression mode for the outer substitution.
Because expression mode reads real tokens, braces and backticks inside it are tracked correctly. Braces that belong to an object literal or an arrow function body do not close the substitution early, and a } inside a string literal is just a character in that string:
console.log(`${JSON.stringify({ a: 1 })}`); // {"a":1}
console.log(`${"}"}`); // }
console.log(`${[1, 2].map(n => { return n * 2; }).join("+")}`); // 2+4This also explains a point about escaping. Inside a substitution you are not in template text, so a backtick there does not need a backslash. It opens a new template. You only escape a backtick when you want a literal backtick character in the text of whichever template you are currently in:
const s = `outer ${`inner \`quoted\``}`;
console.log(s); // outer inner `quoted`The escaped backticks belong to the inner template's text. The unescaped ones open and close that inner template.
Building Lists with map and join
The most common nesting pattern turns an array into repeated markup. map turns each item into a string using an inner template, and join glues those strings together:
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>Read it from the inside out:
- `
<li>${item}</li>` runs once per item. items.map(...)produces the array["<li>a</li>", "<li>b</li>"]..join("")produces the single string"<li>a</li><li>b</li>".- The outer template wraps it in
<ul>and</ul>.
The Forgotten join
If you leave out join, the substitution receives an array. String conversion of an array calls its toString, which joins elements with commas. The output looks almost right, and that makes the bug easy to miss:
const items = ["a", "b"];
const broken = `<ul>${items.map(item => `<li>${item}</li>`)}</ul>`;
console.log(broken); // <ul><li>a</li>,<li>b</li></ul>In a browser, the stray commas show up as visible text between list items. Whenever a substitution contains map, check that a join follows it.
Empty Arrays
[].map(...).join("") is the empty string, so an empty array gives <ul></ul>. That is often fine, but if you want a placeholder, nest a ternary around the list:
function renderList(items) {
return `<ul>${
items.length
? items.map(item => `<li>${item}</li>`).join("")
: `<li class="empty">No items</li>`
}</ul>`;
}
console.log(renderList(["x"])); // <ul><li>x</li></ul>
console.log(renderList([])); // <ul><li class="empty">No items</li></ul>Line breaks inside a substitution are part of the expression, not part of the string. You can spread a long substitution across lines, as above, without adding any whitespace to the output. Only line breaks in template text end up in the result.
Conditional Pieces and Falsy Values
A short way to include a piece only sometimes is cond && ...``. Inside a template, this goes wrong in two ways:
const isNew = false;
const count = 0;
console.log(`<p>Item${isNew && ` <b>new</b>`}</p>`); // <p>Itemfalse</p>
console.log(`<p>${count && `${count} unread`}</p>`); // <p>0</p>When the condition is falsy, && returns the condition itself, and the template converts it to a string: "false" or "0". null and undefined give "null" and "undefined" the same way. Use a ternary with an explicit empty string instead:
const isNew = false;
const count = 0;
console.log(`<p>Item${isNew ? ` <b>new</b>` : ""}</p>`); // <p>Item</p>
console.log(`<p>${count > 0 ? `${count} unread` : ""}</p>`); // <p></p>Evaluation Order
Substitutions are evaluated left to right. A nested template is evaluated completely, producing a string, before the outer template moves to its next substitution. You can see this with a function that records each call:
const log = [];
const t = (label) => { log.push(label); return label; };
const s = `${t("A")} ${`${t("B")}-${t("C")}`} ${t("D")}`;
console.log(s); // A B-C D
console.log(log.join("")); // ABCDThis matters when substitutions have side effects, such as incrementing a counter to number items. It also means the outer template never sees the inner template's parts. It only receives the finished string. This becomes important with tagged templates, covered in the next chapter. A tag on the outer template gets the inner result as one opaque value, and a tag on the inner template runs before the outer one is assembled.
Two Levels Deep: A Table
Nesting can go as deep as the data. Here each row has a list of languages, so there is a map inside a map:
const rows = [
{ name: "Ada", langs: ["JS", "Python"] },
{ name: "Linus", langs: ["C"] }
];
const table = `<table>${rows.map(row => `<tr><td>${row.name}</td><td>${row.langs.map(lang => `<code>${lang}</code>`).join(", ")}</td></tr>`).join("")}</table>`;
console.log(table);
// <table><tr><td>Ada</td><td><code>JS</code>, <code>Python</code></td></tr><tr><td>Linus</td><td><code>C</code></td></tr></table>It works, but it is hard to read and hard to change. You have to count backticks and braces to see where each level ends, and editor support is the only thing between a typo and a confusing syntax error.
Extracting Helper Functions
The fix is the same as for any deeply nested expression: give each level a name. Each helper returns a string from one shallow template:
const rows = [
{ name: "Ada", langs: ["JS", "Python"] },
{ name: "Linus", langs: ["C"] }
];
const renderLang = (lang) => `<code>${lang}</code>`;
const renderRow = (row) =>
`<tr><td>${row.name}</td><td>${row.langs.map(renderLang).join(", ")}</td></tr>`;
const renderTable = (rows) =>
`<table>${rows.map(renderRow).join("")}</table>`;
console.log(renderTable(rows));
// <table><tr><td>Ada</td><td><code>JS</code>, <code>Python</code></td></tr><tr><td>Linus</td><td><code>C</code></td></tr></table>The output is identical. Each function nests at most one map inside its template, and each one can be tested on its own. A reasonable rule of thumb: if a substitution contains a template that itself contains a map, move the inner part into a function.
Whitespace in Nested Multiline Templates
When you want readable, indented output, multiline templates and nesting interact in ways that can surprise you. Each template contributes exactly the whitespace in its own text. Indentation in the source of the outer template does not get applied to lines produced by the inner one.
const items = ["a", "b"];
const html = `
<ul>
${items.map(item => `<li>${item}</li>`).join("\n")}
</ul>`;
console.log(JSON.stringify(html));
// "\n<ul>\n <li>a</li>\n<li>b</li>\n</ul>"The first <li> is indented because the two spaces before ${ are outer template text. The second <li> follows the "\n" from join, and nothing indents it. To indent every item, put the indentation into the separator, or into the inner template itself:
const items = ["a", "b"];
const html = `
<ul>
${items.map(item => ` <li>${item}</li>`).join("\n")}
</ul>`.trim();
console.log(JSON.stringify(html));
// "<ul>\n <li>a</li>\n <li>b</li>\n</ul>"Here each inner template carries its own two spaces, the separator is a plain newline, and .trim() removes the leading newline that comes from starting the outer template on its own line. For HTML that a browser renders, this whitespace rarely matters. For text output such as emails, CLI messages, or generated code, it does, and you should check it with JSON.stringify the way these examples do.
A Warning About Data
Nesting gives you structure, but it does not change what a substitution does: it inserts the converted value unchanged. In ` <li>${item}</li> , if item comes from a user and contains <script>`, that markup goes straight into your HTML. Deep nesting makes this easy to overlook, because the risky substitution may sit three levels down inside a helper.
Common Errors at a Glance
| Symptom | Cause | Fix |
|---|---|---|
| Commas between generated items | `map` result inserted without `join` | Add `.join("")` or another separator |
| `false`, `0`, `null`, or `undefined` in output | `&&` or a missing value in a substitution | Use a ternary with `""` as the fallback |
| Only the first generated line is indented | Indentation is outer text, not part of each item | Put indentation in the inner template or the separator |
| Unexpected `SyntaxError` near a backtick | A brace or backtick is missing at one nesting level | Extract levels into helper functions and recount |
| User-supplied markup appears in the page | Substitutions insert values unchanged | Escape values before inserting them |
Exercises
Exercise
What does this code print, and why? const tags = ["js", "css"]; console.log(Tags: ${tags.map(t => #${t})});
Show answer
It prints "Tags: #js,#css". The map call returns the array ["#js", "#css"], and there is no join. String conversion of an array uses its toString, which joins the elements with commas. Adding .join(" ") would print "Tags: #js #css".
Exercise
Write a function renderMenu(links) that takes an array of objects like { href: "/a", label: "A", active: true } and returns a nav element containing one anchor per link. Active links get class="active"; inactive links get no class attribute at all. An empty array should return <nav></nav>.
Show answer
const renderLink = (link) => <a href="${link.href}"${link.active ? class="active" : ""}>${link.label}</a>; const renderMenu = (links) => <nav>${links.map(renderLink).join("")}</nav>; For example, renderMenu([{ href: "/a", label: "A", active: true }, { href: "/b", label: "B", active: false }]) returns <nav><a href="/a" class="active">A</a><a href="/b">B</a></nav>. The ternary returns "" for inactive links, so no "false" appears, and an empty array maps to an empty string, so the result is <nav></nav>.
Exercise
In what order are the functions called in ${a()} ${${b()} ${c()}} ${d()}, and does the outer template receive the inner template's separate parts or a single string?
Show answer
The calls run in the order a, b, c, d, because substitutions are evaluated left to right and the inner template is evaluated completely when the outer template reaches it. The outer template receives only the inner template's finished string as one value. It never sees the inner template's separate text parts or values.