Sub topic 4
Escaping Backticks and Dollar-Brace Sequences
This chapter assumes you can write basic template literals with backticks and ${} interpolation, and that you know how backslash escapes such as \n and \" work in single- and double-quoted strings.
A template literal gives two character sequences a special meaning. A backtick ends the literal. A dollar sign followed by an opening brace, ${, starts a substitution. If you want either one to appear as plain text, you have to escape it. Most other characters, including single and double quotes, can be written as they are.
How the Parser Reads a Template
The JavaScript engine reads a template literal one character at a time. Some characters change what happens next.
The parser checks the backslash first. That is why \ and \${` work: the backslash takes the next character before the parser can treat it as special.
Escaping a Backtick
To put a backtick inside a template literal, write ` \ ``:
const tip = `Run \`npm test\` before committing.`;
console.log(tip); // Run `npm test` before committing.If you leave out the backslash, the template ends at the second backtick. What follows is then read as code, which usually causes a SyntaxError.
Quotes need no escaping, so templates work well for text that contains both kinds of quote:
const line = `She said "it's fine" and left.`;
console.log(line); // She said "it's fine" and left.Escaping `${`
A dollar sign is only special when an opening brace comes right after it. A dollar sign on its own, or a brace on its own, is plain text:
const price = 5;
console.log(`Cost: $${price}`); // Cost: $5
console.log(`Braces {} and $ alone`); // Braces {} and $ aloneIn $${price}, the first $ is followed by another $, so it is literal. The second $ is followed by {, so it starts a substitution.
To show the characters ${ as text, break the sequence with a backslash. There are two ways to do it, and both give the same result:
const price = 5;
console.log(`Literal: \${price}`); // Literal: ${price}
console.log(`Literal: $\{price}`); // Literal: ${price}\$ produces a dollar sign. \{ produces a brace. In both cases the parser never sees $ directly followed by {, so no substitution starts.
Quick Reference
| You write | Result | Why |
|---|---|---|
| `` \` `` | `` ` `` | Escaped backtick does not end the template |
| `\${x}` | `${x}` | Escaped `$` cannot start a substitution |
| `$\{x}` | `${x}` | Escaped `{` breaks the `${` pair |
| `$x` or `$ {x}` | `$x` or `$ {x}` | `$` is not directly followed by `{` |
| `\\` | `\` | Escaped backslash |
| `` ${"`"} `` | `` ` `` | A substitution can return a backtick from an ordinary string |
Generating Code That Contains Templates
You need escaping most often when one program writes JavaScript source for another, for example in a code generator or a build script. The output contains backticks and ${, and some parts of it still need real interpolation:
const varName = "user";
const snippet = `console.log(\`Hi, \${${varName}.name}\`);`;
console.log(snippet); // console.log(`Hi, ${user.name}`);Read the template from left to right. ` \ ` gives a literal backtick. \${ gives a literal ${. ${varName} is a real substitution that inserts user. Then .name}` is plain text, because a closing brace with no open substitution means nothing special.
Common Errors
- An unescaped backtick in the text. The template ends early, and the rest of the line is parsed as code.
- A
${that is never closed. `Price: ${is aSyntaxError, because the parser expects an expression and a}`. - Backslashes inside a substitution. Code inside
${...}is ordinary JavaScript, not template text. In `${"a\b"}`the backslash belongs to the double-quoted string, which happens to accept\`` as a plain backtick. - Old-style escapes. Octal escapes such as
\1, and malformed escapes such as a\uwith no valid code after it, are syntax errors in untagged templates. A later chapter shows how tagged templates handle them.
Exercise
What does this code print, and why? const n = 2; console.log(\${n}\ costs $${n * 10}, not \${n});
Show answer
It prints: 2 costs $20, not ${n}. The escaped backticks are literal. The first ${n} is a real substitution that inserts 2. In $${n 10}, the first $ is literal and ${n 10} evaluates to 20. The final \${n} is escaped, so it stays as the text ${n}.
Exercise
Write a template literal that, given const field = "id", produces exactly the string row[${id}].
Show answer
row[\\${${field}}\] gives row[ and an escaped backtick, then an escaped ${ as text, then the real substitution ${field} that inserts id, then a literal }, an escaped backtick, and ]. The result is row[${id}].