Sub topic 2
Embedding Expressions with ${}
A template literal becomes useful once you put values inside it. The ${} syntax, called a substitution, lets you place any JavaScript expression inside a string. The engine evaluates that expression and inserts the result. This chapter covers what may go inside ${}, when and in what order those expressions run, and the mistakes intermediate developers make most often.
This chapter assumes you know JavaScript variables, expressions, and functions, and that you have used ordinary single-quoted and double-quoted strings. It also assumes you have read the previous chapter on backtick syntax. Later chapters cover how values are converted to strings, how to escape ${, and how to nest templates, so this chapter only touches on those topics.
The Basic Form
A substitution starts with a dollar sign immediately followed by an opening brace, ${. It ends at the matching closing brace, }. Everything between the two braces is parsed as a JavaScript expression.
const name = "Ada";
const count = 3;
console.log(`Hello, ${name}! You have ${count * 2} new messages.`);
// Hello, Ada! You have 6 new messages.The template has two substitutions. The first reads a variable. The second computes count * 2. Both results are turned into strings and joined with the surrounding text.
Compare the same output written with + concatenation:
const name = "Ada";
const count = 3;
console.log("Hello, " + name + "! You have " + (count * 2) + " new messages.");
// Hello, Ada! You have 6 new messages.The concatenated version needs extra quotes, extra + operators, and parentheses around count * 2 to make the meaning clear. In the template version, the text reads in order and each value sits where it will appear.
What Counts as an Expression
The rule is simple: anything that produces a value can go inside ${}. That covers more than variable names.
| Kind of expression | Example inside a template | Result | Column | Column |
|---|---|---|---|---|
| Variable | `${user}` | value of `user` | ||
| Property access | `${user.name}` or `${user["first-name"]}` | property value | ||
| Arithmetic | `${price * qty}` | the product | ||
| Function or method call | `${name.toUpperCase()}` | return value | ||
| Conditional (ternary) | `${n === 1 ? "item" : "items"}` | one of two strings | ||
| Logical operators | `${nickname \ | \ | name}`, `${title ?? "Untitled"}` | first suitable operand |
| Array method chain | `${tags.filter(Boolean).join(", ")}` | joined string | ||
| Immediately invoked function | `${(() => { const x = 2; return x * x; })()}` | `4` | ||
| `await` (inside an async function) | `${await loadName()}` | resolved value |
Here is a runnable example that uses several of these together:
const user = { name: "grace", nickname: "", unread: 1, tags: ["admin", "", "ops"] };
const line =
`${user.nickname || user.name.toUpperCase()} has ` +
`${user.unread} unread ${user.unread === 1 ? "message" : "messages"} ` +
`[${user.tags.filter(Boolean).join(", ")}]`;
console.log(line);
// GRACE has 1 unread message [admin, ops]Note the pluralization with the ternary operator. Picking between singular and plural forms is one of the most common uses of a ternary inside a substitution.
Choosing between `||` and `??`
Both operators supply a fallback, but they disagree about which values count as missing. || falls back for any falsy value, including 0 and "". ?? falls back only for null and undefined.
const stock = 0;
console.log(`In stock: ${stock || "unknown"}`); // In stock: unknown
console.log(`In stock: ${stock ?? "unknown"}`); // In stock: 0When 0 or the empty string is a real value, use ??.
Using `await` inside a substitution
A substitution is an ordinary expression position, so await works there inside an async function:
function loadName() {
return Promise.resolve("Linus");
}
async function greet() {
return `Welcome back, ${await loadName()}!`;
}
greet().then(console.log); // Welcome back, Linus!The template does not produce its string until the awaited promise settles.
Statements Are Not Allowed
A substitution must contain an expression. It cannot contain a statement. if, for, while, switch, let, and const are statements, so each of the following is a SyntaxError:
// SyntaxError: these lines are shown for illustration and will not parse.
// `${if (ok) { "yes" }}`
// `${const x = 1}`
// `${for (const t of tags) t}`Each statement has an expression form you can use instead:
| Statement you wanted | Expression to use instead |
|---|---|
| `if / else` | ternary `cond ? a : b`, or `cond && a` |
| `for` loop over items | `items.map(...).join("")` |
| `switch` | object lookup, e.g. `labels[status] ?? "?"` |
| several statements | a helper function, or an IIFE |
const status = "paused";
const labels = { running: "Running", paused: "Paused", stopped: "Stopped" };
const items = ["x", "y", "z"];
console.log(`State: ${labels[status] ?? "Unknown"}`); // State: Paused
console.log(`Items: ${items.map((s, i) => i + 1 + "." + s).join(" ")}`);
// Items: 1.x 2.y 3.zAn IIFE (immediately invoked function expression) works when you need several steps, but it hurts readability. If a substitution needs more than one line of logic, move that logic into a named function and call it from the template.
When and in What Order Substitutions Run
Left to right, once
The engine evaluates the substitutions of an untagged template from left to right. It converts each result to a string before it moves on to the next substitution. Each expression runs exactly once each time the template is evaluated.
let calls = 0;
function next(label) {
calls++;
return `${label}#${calls}`;
}
console.log(`${next("a")} then ${next("b")} then ${next("c")}`);
// a#1 then b#2 then c#3
console.log(calls); // 3Side effects therefore happen in source order. Even so, avoid writing templates whose output depends on side effects. A template should describe output, not trigger work.
Eager, not deferred
A template literal is evaluated at the moment the line runs. Its result is an ordinary string with the current values baked in. It does not remember the variables and does not update when they change.
let city = "Oslo";
const message = `Weather for ${city}`;
city = "Lima";
console.log(message); // Weather for OsloDevelopers who have used template engines such as Handlebars sometimes expect a reusable template. To get one, wrap the literal in a function so it is evaluated again on each call:
const weatherFor = (city) => `Weather for ${city}`;
console.log(weatherFor("Oslo")); // Weather for Oslo
console.log(weatherFor("Lima")); // Weather for LimaThis pattern, a small arrow function that returns a template literal, is the usual way to build reusable string templates in plain JavaScript.
Errors abort the whole string
If any expression throws, or its value cannot be converted, the template produces no string at all. The exception propagates as if it had been thrown anywhere else in the expression.
const order = { id: 7 };
try {
console.log(`Order ${order.id} ships to ${order.address.city}`);
} catch (err) {
console.log(err instanceof TypeError); // true
}order.address is undefined, so reading .city throws a TypeError. Optional chaining together with a fallback produces a string instead:
const order = { id: 7 };
console.log(`Order ${order.id} ships to ${order.address?.city ?? "an unknown city"}`);
// Order 7 ships to an unknown cityAn undeclared variable inside a substitution throws a ReferenceError for the same reason: the code inside ${} is ordinary code.
Common Errors
Using quotes instead of backticks
Substitutions only work inside backticks. Inside single or double quotes, ${name} is ordinary text.
const name = "Ada";
console.log("Hello, ${name}"); // Hello, ${name}
console.log(`Hello, ${name}`); // Hello, AdaLinters such as ESLint flag this with the no-template-curly-in-string rule. Turn it on.
A space between `$` and `{`
The dollar sign and the brace must be adjacent. A $ that is not immediately followed by { is a literal character.
const total = 42;
console.log(`Total: $ {total}`); // Total: $ {total}
console.log(`Total: ${total}`); // Total: 42Printing a literal dollar sign before a value
Because a lone $ is literal, you can put a currency sign directly before a substitution:
const price = 9.99;
console.log(`Price: $${price.toFixed(2)}`); // Price: $9.99The first $ is plain text. The second $ starts the substitution. To print the characters ${ themselves, you need escaping, which the chapter on escaping backticks and dollar-brace sequences covers.
Unwanted `undefined`, `null`, and `[object Object]`
A substitution inserts whatever the expression produces, even when that value is useless in output:
const profile = { name: "Ada" };
console.log(`Age: ${profile.age}`); // Age: undefined
console.log(`Manager: ${null}`); // Manager: null
console.log(`Profile: ${profile}`); // Profile: [object Object]
console.log(`Profile: ${JSON.stringify(profile)}`); // Profile: {"name":"Ada"}None of these throw, so they slip into user-facing text without any error. Provide fallbacks with ??, and format objects explicitly. The rules that decide how each type becomes a string are covered in the chapter on how interpolated values become strings.
The comma operator
A comma inside a substitution is the comma operator. It evaluates both operands and keeps only the last one. Developers sometimes write a comma when they meant to show two values:
const first = "Ada";
const last = "Lovelace";
console.log(`${first, last}`); // Lovelace
console.log(`${first} ${last}`); // Ada Lovelace
console.log(`${[first, last]}`); // Ada,LovelaceBraces inside substitutions
The parser matches braces, so object literals, arrow-function bodies, and destructuring all work inside ${}:
const pick = ({ a }) => a;
console.log(`${pick({ a: "ok" })}`); // ok
console.log(`${(() => { return "block body"; })()}`); // block bodyA brace that is not balanced, such as one missing a closing }, makes the parser read on into the rest of the file, and the resulting SyntaxError can be reported far from the actual mistake. If you see an "unterminated template" error, check your braces first.
Interpolation Does Not Sanitize
A substitution inserts the value exactly as it converts to a string. It does not escape HTML, quote SQL, or handle shell metacharacters.
const comment = "<img src=x onerror=alert(1)>";
const html = `<p>${comment}</p>`;
console.log(html); // <p><img src=x onerror=alert(1)></p>If that string reaches innerHTML, the browser runs the attacker's code. Template literals make building strings easier, but they are no safer than concatenation. The chapter on building an escaping tag shows how tagged templates can fix this.
Exercises
Exercise
What does this code print, and why? let n = 1; const s = ${n++} + ${n++} = ${n}; console.log(s);
Show answer
It prints "1 + 2 = 3". Substitutions are evaluated left to right, once each. The first n++ yields 1 and sets n to 2. The second yields 2 and sets n to 3. The third substitution reads n as 3.
Exercise
Rewrite ${if (items.length === 0) { "empty" } else { items.length + " items" }} so that it is valid and prints "empty", "1 item", or "N items" correctly.
Show answer
Use nested ternaries, which are expressions: ${items.length === 0 ? "empty" : ${items.length} ${items.length === 1 ? "item" : "items"}}. Or, more readably, move the logic into a function: const describe = (n) => n === 0 ? "empty" : n === 1 ? "1 item" : ${n} items; and write ${describe(items.length)}.
Exercise
A colleague writes const greeting = Hi, ${user.name}; at the top of a module and expects it to update after user.name changes later. Explain why it does not update, and show a fix.
Show answer
The template literal is evaluated once, when the line runs, and produces a plain string with the name that existed at that moment. The string has no link to user. To get a fresh result each time, wrap the template in a function: const greeting = () => Hi, ${user.name}; and call greeting() whenever the text is needed.
Exercise
What does ${price ?? "N/A"} print when price is 0, and what does ${price || "N/A"} print? Which one should a shop page use?
Show answer
The ?? version prints "0" because it only falls back for null or undefined. The || version prints "N/A" because 0 is falsy. A shop page should use ?? so that a real price or stock count of 0 is shown rather than hidden.