Sub topic 1
A Quick Refresher on Template Literals
Tagged templates are built on ordinary template literals. A tag changes what happens to the pieces of a template literal. It does not change how those pieces are written. Before we look at tags, this chapter reviews how an untagged template literal is parsed and evaluated, and points out the details that matter later: how substitutions become strings, when they are evaluated, and how escapes and line breaks are handled.
Prerequisites
This chapter assumes you are comfortable with:
- JavaScript functions, including arrow functions and rest parameters (
...args). - Arrays and
Array.prototype.reduceandmap. - String escape sequences such as
\n(newline) and\t(tab). - Having seen a template literal with backticks at least once.
You do not need to know anything about tags yet. Every example here runs in Node.js or a browser console.
The Syntax in One Minute
A template literal is a string literal written between backticks (` `) instead of single or double quotes. Inside it, ${ expression }` marks a substitution. A substitution is a slot where JavaScript evaluates an expression and inserts the result.
const item = 'coffee';
const price = 3.5;
const qty = 2;
console.log(`${qty} x ${item} = $${(price * qty).toFixed(2)}`);
// 2 x coffee = $7.00Any expression is allowed inside ${}: arithmetic, function calls, ternaries, even another template literal. Statements such as if or for are not allowed. The $$ in the example is a literal dollar sign followed by a substitution. A $ only starts a substitution when a { follows it directly.
The literal splits into two kinds of parts:
| Part | Example from above | Known when? |
|---|---|---|
| Static text | `" x "`, `" = $"` | When the code is parsed |
| Substitution | `qty`, `item`, `(price * qty).toFixed(2)` | Each time the line runs |
This split between fixed text and runtime values is the main idea behind tagged templates. An untagged literal joins the parts into one string. A tag receives them separately.
How an Untagged Literal Is Evaluated
The steps:
- The static text is fixed when the code is parsed, with escape sequences already processed.
- Each time the expression runs, the substitutions are evaluated from left to right.
- Each result goes through the spec's
ToStringoperation. - Text and converted values are joined into a single string.
Steps 3 and 4 are exactly what a tag replaces. Before that, two of these steps behave in ways that surprise people.
Substitutions Use ToString, Not +
You might expect ` ${x} to behave like '' + x. It usually does, but the conversion differs. A template literal converts with a preference for strings, so an object's toString method wins. The + operator uses the "default" hint, and for ordinary objects that means valueOf` runs first.
const obj = {
valueOf() { return 42; },
toString() { return 'forty-two'; },
};
console.log(`${obj}`); // forty-two
console.log('' + obj); // 42
console.log(String(obj)); // forty-twoSymbols are a sharper case. String(symbol) works, but implicit conversion in a template literal throws:
const id = Symbol('id');
console.log(String(id)); // Symbol(id)
try {
console.log(`${id}`);
} catch (err) {
console.log(err instanceof TypeError); // true
}Here is how common values come out:
| Value | `` `${value}` `` |
|---|---|
| `null` | `"null"` |
| `undefined` | `"undefined"` |
| `[1, 2, 3]` | `"1,2,3"` |
| `{ a: 1 }` | `"[object Object]"` |
| `Symbol('x')` | throws `TypeError` |
| `10n` (BigInt) | `"10"` |
Substitutions Are Evaluated Eagerly
A template literal is not a reusable template. It is an expression, evaluated once at the point where it appears. Changing a variable afterwards has no effect on a string that already exists.
let n = 1;
const msg = `n is ${n}`;
n = 2;
console.log(msg); // n is 1
const makeMsg = () => `n is ${n}`;
console.log(makeMsg()); // n is 2If you want a template you can fill in later, wrap the literal in a function. Evaluation also runs strictly left to right, so side effects happen in source order:
let counter = 0;
const next = () => ++counter;
console.log(`${next()}-${next()}-${next()}`); // 1-2-3Multiline Strings and Whitespace
Template literals can span lines. Every character between the backticks becomes part of the string, including newlines and indentation.
function render() {
return `
<ul>
<li>One</li>
</ul>`;
}
console.log(JSON.stringify(render()));
// "\n <ul>\n <li>One</li>\n </ul>"The string starts with a newline and keeps the four spaces of indentation from the source. This matters for output where whitespace counts, such as Markdown, YAML, or test snapshots. People often reach for a "dedent" helper here, and dedent helpers are usually written as tags.
Two smaller line-handling details:
- A backslash at the very end of a line is a line continuation. The backslash and the newline are both removed.
- Line endings are normalized. A file saved with Windows
\r\nendings still produces\ninside a template literal, so the result does not depend on the editor's settings.
const long = `This is one \
logical line.`;
console.log(long); // This is one logical line.Escapes Inside Backticks
Template literals support the same escape sequences as quoted strings (\n, \t, \u00e9, \x41, and so on), plus two of their own:
- `
\`` gives a literal backtick. \${gives a literal${without starting a substitution.
console.log(`Use \`backticks\` and write \${name} literally.`);
// Use `backticks` and write ${name} literally.In an untagged template literal, a malformed escape such as \u that is not followed by valid hex digits is a syntax error, just as it is in a quoted string. Tagged templates relax this rule, which a later chapter explains. For now, remember that the text you type and the string you get are two different things: \n in the source becomes one newline character in the result. Later chapters call these two forms "raw" and "cooked."
Nesting Template Literals
Because a substitution can hold any expression, it can contain another template literal. This is common when building lists:
const items = ['apples', 'pears'];
const list = `<ul>${items.map((i) => `<li>${i}</li>`).join('')}</ul>`;
console.log(list);
// <ul><li>apples</li><li>pears</li></ul>If you leave out .join(''), the array is converted with ToString and its elements are joined with commas: <ul><li>apples</li>,<li>pears</li></ul>. Stray commas in generated HTML usually come from this mistake.
Common Errors Recap
| Mistake | Symptom | Fix |
|---|---|---|
| Using `'` or `"` instead of backticks | `${name}` appears literally in output | Use backticks |
| Expecting lazy evaluation | String shows old values | Wrap the literal in a function |
| Forgetting `.join('')` on mapped arrays | Commas between elements | Join explicitly |
| Indenting multiline literals with the code | Unwanted leading spaces and newline | Trim, dedent, or start text right after the backtick |
| Interpolating a Symbol | `TypeError` | Convert with `String(sym)` or `sym.description` |
| Interpolating untrusted input into HTML/SQL | Injection vulnerabilities | Use an escaping tag or parameterized queries |
Where Tags Come In
Everything above describes the default behavior: split, evaluate, convert, concatenate. If you put a function name directly before the opening backtick, JavaScript still does the split and the evaluation, but it skips the conversion and concatenation. It calls your function with the parts instead. The next chapter shows exactly what that call looks like.
Exercise
What does this code print, and why?
const user = { name: 'Ada', toString() { return 'User(Ada)'; }, valueOf() { return 1; } };
let greeting = Hi ${user};
user.name = 'Grace';
console.log(greeting, '|', 'Hi ' + user);
Show answer
It prints "Hi User(Ada) | Hi 1". The template literal converts with a string preference, so toString runs and gives "User(Ada)". The literal is evaluated once, on the line where it appears, and changing user.name later cannot affect it (and toString returns a fixed string anyway). The + operator uses the default hint, so valueOf runs first and gives 1.
Exercise
Write a function line(label, value) that returns a template literal producing exactly "label: value" followed by a newline, with no leading whitespace, and where a value of null shows as "(none)". What does line('city', null) return?
Show answer
One solution is: const line = (label, value) => ${label}: ${value ?? '(none)'}\n; The call line('city', null) returns "city: (none)\n". Without the ?? fallback, null would be converted to the text "null".
Exercise
Why does <p>${['a', 'b']}</p> produce "<p>a,b</p>", and what would print for \${x} costs $${5}?
Show answer
The array is converted with ToString, which calls Array.prototype.join with a comma separator, so you get "a,b". The second literal prints "${x} costs $5": the \${ escape is a literal "${", and the first $ in $${5} is literal text followed by a substitution that evaluates to 5.