Sub topic 2
Embedding Expressions with ${}
This chapter assumes you know JavaScript variables, expressions, and functions, and that you can write a basic template literal with backticks. The goal is a working model of what can go inside ${}, when it runs, and the mistakes people make most often with it.
The Rule: Any Expression, Not Statements
A substitution is the ${ ... } part of a template literal. It can hold any JavaScript expression, meaning any piece of code that produces a value. JavaScript evaluates the expression and inserts the result into the string at that position.
Simple variables are the most common case, but you can use much more:
const price = 19.99;
const qty = 3;
const user = { first: "Ada", last: "Lovelace" };
const items = ["pen", "ink"];
console.log(`Total: ${(price * qty).toFixed(2)}`);
// Total: 59.97
console.log(`Name: ${user.first} ${user.last.toUpperCase()}`);
// Name: Ada LOVELACE
console.log(`Items: ${items.length} (${items.join(", ")})`);
// Items: 2 (pen, ink)
console.log(`Status: ${qty > 0 ? "in stock" : "sold out"}`);
// Status: in stockArithmetic, property access, method calls, function calls, and the conditional (ternary) operator all work, because each of them is an expression. Statements do not work. if, for, while, const, and return cannot appear directly inside ${}. If you need a branch, use a ternary or &&/||. If you need a loop, use an array method such as map followed by join.
| Inside `${}` | Allowed? | Alternative |
|---|---|---|
| `a + b`, `fn(x)`, `obj.prop` | Yes | — |
| `cond ? x : y` | Yes | — |
| `if (cond) { ... }` | No, SyntaxError | `cond ? x : y` |
| `for (...) { ... }` | No, SyntaxError | `arr.map(...).join("")` |
| Empty `${}` | No, SyntaxError | Remove it, or use `${""}` |
When the Expression Runs
A template literal is evaluated at the moment execution reaches it, just like a + b. The result is an ordinary string, and it does not stay linked to the variables that produced it.
let count = 1;
const message = `Count is ${count}`;
count = 5;
console.log(message); // Count is 1
const makeMessage = (n) => `Count is ${n}`;
console.log(makeMessage(count)); // Count is 5This catches people who expect a template to act like a reusable pattern. If you want to fill in a template more than once with different values, put it in a function and pass the values as arguments.
Substitutions are evaluated left to right, each one exactly once. This matters when an expression has side effects:
const log = [];
const step = (label) => {
log.push(label);
return label;
};
const s = `${step("a")}-${step("b")}-${step("c")}`;
console.log(s); // a-b-c
console.log(log); // [ 'a', 'b', 'c' ]Each result is converted to a string before it is joined. The exact conversion rules, and how they differ from + concatenation, have their own chapter. For now, numbers and strings appear as you would expect.
Common Errors
The mistakes that come up most often have nothing to do with the expression itself. They come from the syntax around it:
const name = "Ada";
console.log("Hello, ${name}"); // Hello, ${name}
console.log('Hello, ${name}'); // Hello, ${name}
console.log(`Hello, $name`); // Hello, $name
console.log(`Hello, {name}`); // Hello, {name}
console.log(`Hello, ${name}`); // Hello, Ada- Wrong quotes. Single and double quotes never interpolate, so
${name}appears literally. Linters such as ESLint'sno-template-curly-in-stringrule flag this. - Missing braces or dollar sign.
$nameand{name}are plain text. You need both$and{}. - Calling a function without parentheses.
${user.getName}inserts the function's source text, not its return value. Write${user.getName()}. - Operator precedence with method calls.
${price * qty.toFixed(2)}callstoFixedonqtyalone. Wrap the arithmetic in parentheses:${(price * qty).toFixed(2)}. - Expecting live updates. As shown above, the string is built once. Changing a variable afterwards does not change the string.
Exercise
What does this code print, and why? let n = 2; const t = \${n} squared is ${n * n}\; n = 10; console.log(t);
Show answer
It prints "2 squared is 4". The template literal is evaluated once, at the moment its line runs, while n is 2. The result is a plain string, so reassigning n to 10 afterwards has no effect on t.
Exercise
Rewrite if (cart.length === 0) { "empty" } else { cart.length + " items" } so it works inside a single template literal that starts with "Cart: ".
Show answer
Use a ternary, because statements are not allowed inside ${}: Cart: ${cart.length === 0 ? "empty" : ${cart.length} items} or, without nesting, Cart: ${cart.length === 0 ? "empty" : cart.length + " items"}.