Sub topic 4
Template Literals and Interpolation
A template literal is a string written between backticks (` ``) instead of quotes. It can hold embedded expressions and can span several lines. This chapter covers how interpolation works, how values become text inside a template, how multi-line templates handle whitespace, and the mistakes people make most often.
This chapter assumes you know basic JavaScript syntax (variables, functions, conditionals), can run code in Node.js or a browser console, and have read the earlier chapters on string literals and immutability. Tag functions and String.raw have their own chapter later, so they are only mentioned here.
The Basic Syntax
A template literal is made of literal text and substitutions. A substitution is ${expression}. JavaScript evaluates the expression, converts the result to a string, and puts it in place of the substitution.
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
const a = 4;
const b = 5;
console.log(`sum: ${a + b}, max: ${Math.max(a, b)}`); // sum: 9, max: 5Any expression is allowed between ${ and }: arithmetic, function calls, property access, ternaries, even another template literal. Statements are not allowed. You cannot put an if block or a for loop inside a substitution. Use a ternary, a function call, or an array method that returns a value instead.
The result is an ordinary string primitive. typeof returns "string", and every string method from the rest of this tutorial works on it.
How a Template Literal Is Evaluated
The engine processes a template literal from left to right. It evaluates each expression in order, converts each result to a string, and joins all the pieces into one new string.
Two details here cause real bugs.
The first is that evaluation happens immediately. A template literal is not a reusable template. It produces a fixed string at the moment the line runs. If you change a variable later, a string you already built does not update.
let count = 1;
const msg = `count is ${count}`;
count = 2;
console.log(msg); // count is 1
// To reuse a template, wrap it in a function
const render = (c) => `count is ${c}`;
console.log(render(count)); // count is 2
console.log(render(10)); // count is 10The second is that side effects in substitutions run in order, left to right. ` ${f()} ${g()} always calls f before g`.
How Values Become Text
Each substitution goes through the abstract ToString operation. For primitives, the result is usually what you expect:
| Value | Result inside `${}` |
|---|---|
| `42` | `"42"` |
| `-0` | `"0"` |
| `true` | `"true"` |
| `null` | `"null"` |
| `undefined` | `"undefined"` |
| `10n` (BigInt) | `"10"` |
| `[1, 2, 3]` | `"1,2,3"` |
| `{ a: 1 }` | `"[object Object]"` |
| `Symbol("x")` | throws `TypeError` |
Objects are the case to watch. Writing a plain object into a template gives [object Object], which you almost never want. Use JSON.stringify or pick the properties you need.
const point = { x: 1, y: 2 };
console.log(`point: ${point}`); // point: [object Object]
console.log(`point: ${JSON.stringify(point)}`); // point: {"x":1,"y":2}
console.log(`point: (${point.x}, ${point.y})`); // point: (1, 2)Symbols cannot be converted implicitly, so ` ${Symbol("x")} throws. Call String(sym) or read sym.description instead. The chapter on converting values to strings covers String()` in detail.
Template Literals Versus the + Operator
Most people treat ` ${x} and "" + x as the same thing. For objects they are not. The + operator converts its operand with the "default" hint, which tries valueOf first. A template literal uses the "string" hint, which tries toString` first.
const obj = {
valueOf() { return 42; },
toString() { return "forty-two"; },
};
console.log("" + obj); // 42
console.log(`${obj}`); // forty-two
console.log(String(obj)); // forty-twoA template literal behaves like String(value) for objects, and + does not. If a class defines both methods, such as Date or a money type, the two forms can produce different text.
Multi-line Strings and Whitespace
A template literal can contain real line breaks. Everything between the backticks is kept, including newlines and indentation.
function report() {
const text = `
Name: Ada
Role: Engineer
`;
return text;
}
console.log(JSON.stringify(report()));
// "\n Name: Ada\n Role: Engineer\n "The output has a leading newline, four spaces before each line, and a trailing newline plus two spaces. That comes from indenting the code. Here are some common fixes:
// 1. Start text right after the backtick and keep lines flush left
const a = `Name: Ada
Role: Engineer`;
// 2. Build from an array of lines
const b = ["Name: Ada", "Role: Engineer"].join("\n");
// 3. Strip the indentation after building
const c = `
Name: Ada
Role: Engineer
`.trim().split("\n").map((line) => line.trim()).join("\n");
console.log(a === b, b === c); // true trueEdge cases in multi-line templates:
- Line endings are normalized. A Windows CRLF (
\r\n) inside a template in the source file becomes\nin the string. If you need\r\n, write the escape explicitly. - A backslash at the very end of a line is a line continuation. The backslash and the newline are both removed, which lets you wrap a long single line in source.
const long = `This sentence is split in source \
but prints on one line.`;
console.log(long); // This sentence is split in source but prints on one line.Escaping Backticks and Dollar Signs
The usual escape sequences (\n, \t, \u{1F600}, \\) all work inside template literals. Two extra characters need care:
- A backtick ends the literal, so write `
\`` to include one. ${starts a substitution, so write\${to include it literally. A$that is not followed by{needs no escape.
console.log(`Use \`npm test\` to run tests`); // Use `npm test` to run tests
console.log(`Price: $5`); // Price: $5
console.log(`Write \${name} for a placeholder`); // Write ${name} for a placeholderSingle and double quotes need no escaping inside backticks. This makes template literals handy for text that contains both, such as SQL fragments or English with apostrophes.
Nesting Templates
A substitution can contain another template literal. This helps with conditional fragments and lists.
const items = ["pen", "ink"];
const summary = `Cart: ${
items.length ? `${items.length} item(s): ${items.join(", ")}` : "empty"
}`;
console.log(summary); // Cart: 2 item(s): pen, ink
const rows = [{ id: 1, name: "a" }, { id: 2, name: "b" }];
const table = rows.map((r) => `${r.id}\t${r.name}`).join("\n");
console.log(table);
// 1 a
// 2 bUse nesting with restraint. When a ternary inside a template holds another template that holds another ternary, move the inner part into a named variable or function.
Common Errors
| Mistake | Symptom | Fix |
|---|---|---|
| Using quotes instead of backticks: `"Hi ${name}"` | Prints `${name}` literally | Use backticks |
| Interpolating an object | `[object Object]` in output | `JSON.stringify` or choose fields |
| Interpolating a missing value | `undefined` or `null` in UI text | Default with `??`: `${name ?? "guest"}` |
| Expecting the string to update | Output shows the old value | Wrap the template in a function |
| Indented multi-line template | Extra spaces and newlines | Keep lines flush, `join("\n")`, or trim |
| Inserting user input into HTML or SQL | Injection vulnerabilities | Escape the values or use parameterized APIs |
The last row matters most. Interpolation does no escaping. ` SELECT * FROM users WHERE name = '${input}' ` is open to SQL injection exactly as string concatenation is. Use your database driver's placeholders. For HTML, use a templating library or a tag function that escapes values. That tag pattern appears in the tagged templates chapter.
Exercises
Exercise
What does this code print, and why? let n = 1; const s = \n=${n}\; n++; console.log(s, \n=${n}\);
Show answer
It prints "n=1 n=2". The first template is evaluated when s is assigned, while n is 1, and the resulting string never changes. The second template is evaluated inside the console.log call, after the increment.
Exercise
Given const t = { valueOf: () => 7, toString: () => "seven" };, what are the values of "" + t and ` ${t} `?
Show answer
"" + t is "7", because + converts with the default hint and calls valueOf first. ` ${t} ` is "seven", because template literals convert with the string hint and call toString first.
Exercise
Write a function label(user) that returns "Hello, NAME (N messages)" using a template literal. It should use "guest" when user.name is null or undefined, and "message" instead of "messages" when the count is 1.
Show answer
const label = (user) => \Hello, ${user.name ?? "guest"} (${user.count} message${user.count === 1 ? "" : "s"})\; For example, label({ name: null, count: 1 }) returns "Hello, guest (1 message)".
Exercise
How do you produce the exact text Cost: ${price} (with the dollar sign and braces) from a template literal?
Show answer
Escape the substitution start: ` Cost: \${price} . Writing $\{price} also works. A $ on its own needs no escape; only the ${` sequence starts a substitution.