Sub topic 6
Nesting Template Literals
This chapter assumes you already know how ${} interpolation works and how values are converted to strings. You should also be comfortable with arrow functions and the array methods map and join.
A template literal is an expression, and the inside of ${} accepts any expression. So the inside of ${} can hold another template literal. This is called nesting. You can use it to build structured output such as HTML lists, tables, and messages whose parts depend on conditions.
Why Nesting Works
When the parser reaches ${, it stops reading string text and starts reading a JavaScript expression. It keeps reading that expression until it finds the matching }. While it reads the expression, a backtick starts a new template literal. It does not close the outer one. The inner literal is complete when its own closing backtick appears, and then the parser goes back to reading the expression.
So the backticks in this example don't conflict with each other:
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>The outer literal builds the <ul> wrapper. The inner literal builds one <li> for each item. map runs the inner template once per element. join("") then merges the results into a single string before the outer template inserts it.
Each inner template is fully evaluated before the outer template builds its string. Substitutions at the same level are evaluated from left to right.
Conditional Fragments
Nesting also works well with the conditional (ternary) operator. You can include a whole formatted fragment only when a condition holds:
function greet(user) {
return `Hi ${user.name}${user.unread > 0 ? `, you have ${user.unread} new messages` : ""}.`;
}
console.log(greet({ name: "Ada", unread: 3 })); // Hi Ada, you have 3 new messages.
console.log(greet({ name: "Ada", unread: 0 })); // Hi Ada.The false branch is an empty string, so it adds nothing to the output. If you wrote user.unread > 0 && ... instead, the false case would insert the text false, because interpolation converts the boolean to a string.
Common Errors
Forgetting `join`
map returns an array. If you interpolate the array directly, it is converted with its default string conversion, and that conversion puts commas between the elements:
const items = ["a", "b"];
console.log(`<ul>${items.map(item => `<li>${item}</li>`)}</ul>`);
// <ul><li>a</li>,<li>b</li></ul>The stray comma is easy to miss in a browser, where it appears as a small mark between list items. Always finish a map with join(""), or join("\n") if you want line breaks.
Losing track of braces and backticks
Every level of nesting adds a ${, a }, and a pair of backticks. If one of them is missing, you get a syntax error far from the real mistake, or a string that silently contains code text. Editors with bracket matching help. A better fix is to nest less.
Unexpected whitespace
If you split a nested template across lines for readability, the line breaks and indentation of the outer literal become part of the output:
const items = ["a", "b"];
const list = `
<ul>
${items.map(item => ` <li>${item}</li>`).join("\n")}
</ul>`;
console.log(JSON.stringify(list));
// "\n<ul>\n <li>a</li>\n <li>b</li>\n</ul>"This output starts with a newline. For HTML that rarely matters. For plain text output or tests that compare exact strings, it does.
Extracting Helper Functions
Deep nesting is hard to read. When a template reaches two or three levels, move each level into its own small function that returns a template literal:
const cell = (content) => `<td>${content}</td>`;
const row = (person) => `<tr>${cell(person.name)}${cell(person.langs.join(", "))}</tr>`;
const table = (people) => `<table>${people.map(row).join("")}</table>`;
const people = [
{ name: "Ada", langs: ["JS", "Python"] },
{ name: "Linus", langs: ["C"] }
];
console.log(table(people));
// <table><tr><td>Ada</td><td>JS, Python</td></tr><tr><td>Linus</td><td>C</td></tr></table>The output is the same as one large nested template would produce. Each function has one job, you can test each one on its own, and people.map(row) reads almost like a sentence.
Exercises
Exercise
What does this code print? const nums = [1, 2, 3]; console.log([${nums.map(n => ${n * n})}]);
Show answer
It prints [1,4,9]. The inner template turns each square into a string. Because there is no join, the array is converted with its default conversion, which puts commas between the elements.
Exercise
Write a function badge(count) that returns "Inbox" when count is 0 and "Inbox (N)" otherwise. Use a nested template literal for the count part.
Show answer
const badge = (count) => Inbox${count > 0 ? (${count}) : ""}; Then badge(0) returns "Inbox" and badge(5) returns "Inbox (5)".
Exercise
Refactor <ol>${steps.map(s => <li><strong>${s.title}</strong>: ${s.text}</li>).join("")}</ol> into helper functions.
Show answer
One solution: const step = (s) => <li><strong>${s.title}</strong>: ${s.text}</li>; const steps = (list) => <ol>${list.map(step).join("")}</ol>; Calling steps(data) gives the same output as the original expression.