Sub topic 1
Writing Strings with Backticks
A template literal is a JavaScript string literal written between backtick characters (` `) instead of single or double quotes. ES2015 added it, and every modern browser and Node.js release supports it. This chapter covers the delimiter itself: what a backtick literal produces, how it compares to quoted strings, which escape sequences it accepts, and where the language won't let you use one. Later chapters cover the features built on top of it, such as ${}` interpolation, multiline text, and tagged templates.
Prerequisites
This chapter assumes you already know:
- JavaScript variables, expressions, and functions, including arrow functions.
- Regular string literals with single and double quotes, and common escapes such as
\nand\". - Arrays and common array methods such as
map,join, andreduce. These matter more in later chapters. - Rest parameters (
...args). These matter for tag functions later on.
You should be able to run code in Node.js or a browser console. Every runnable example here prints its result with console.log.
What a Backtick Literal Produces
A template literal with no ${} inside evaluates to an ordinary string primitive. It isn't a special object or a new type. Once the expression has run, nothing records which delimiter you used.
const a = 'hello';
const b = "hello";
const c = `hello`;
console.log(typeof c); // string
console.log(a === c, b === c); // true true
console.log(c.length); // 5
console.log(`hello`.toUpperCase()); // HELLO
console.log(c instanceof String); // falseThe result is a primitive, so instanceof String is false, just as it is for 'hello'. All string methods work through the usual auto-boxing, and so do comparisons, switch cases, Map keys, and every other place a string can go.
The specification calls a backtick literal with no substitutions a NoSubstitutionTemplate. You can think of it as a third way of quoting, and in most code it is exactly that. The differences from quoted strings come from two features. One is substitution with ${. The other is the rule that the literal may span lines. Those two features also explain the restrictions covered later in this chapter.
Comparing the Three Delimiters
| Feature | `'single'` | `"double"` | `` `backtick` `` |
|---|---|---|---|
| Result type | string primitive | string primitive | string primitive (untagged) |
| Contains `'` without escaping | no | yes | yes |
| Contains `"` without escaping | yes | no | yes |
| Contains `` ` `` without escaping | yes | yes | no |
| Raw line breaks allowed | no | no | yes |
| `${expr}` substitution | no, literal text | no, literal text | yes |
| Legacy octal escapes like `\01` | allowed in sloppy mode | allowed in sloppy mode | always a SyntaxError |
| Valid as object literal key | yes | yes | no |
| Valid as `import` specifier | yes | yes | no |
| Valid in JSON | no | yes | no |
The quoting rows explain why many developers switch to backticks for text that contains both kinds of quotes. In a backtick literal, the only character you must escape to keep the literal from ending is the backtick.
console.log(`It's "fine"`); // It's "fine"
console.log('It\'s "fine"'); // It's "fine"
console.log("It's \"fine\""); // It's "fine"
console.log(`SQL: WHERE name = 'O"Brien'`); // SQL: WHERE name = 'O"Brien'Inside a template literal, ${ is also special, because it starts a substitution. The chapter on escaping covers how to write ${ as literal text and how to put a backtick inside a template.
How the Parser Reads a Backtick Literal
The parser treats a template literal as a token, or as a series of tokens when it contains substitutions. It scans the text from the opening backtick and stops at one of three things:
- An unescaped backtick, which ends the literal.
- The two-character sequence
${, which starts an embedded expression. Parsing switches back to normal JavaScript until the matching}, then resumes template scanning. - A backslash, which starts an escape sequence that gets decoded into the string's "cooked" value.
Any other character, including a raw line break, becomes part of the string.
The rest of this chapter follows from this model. A lone $ with no { after it is ordinary text, and so is a { with no $ in front of it:
console.log(`Price: $5 {approx}`); // Price: $5 {approx}
console.log(`$ {not a substitution}`); // $ {not a substitution}The second line has a space between $ and {, so the parser never sees the ${ sequence.
Escape Sequences Still Work
Backticks don't turn off escape sequences. An untagged template literal decodes \n, \t, \\, \', \", \xHH, \uHHHH, \u{...}, and line continuations the same way quoted strings do.
const s = `tab:\there\nnewline, hex \x41, unicode \u00e9, astral \u{1F600}`;
console.log(s);
// tab: here
// newline, hex A, unicode é, astral 😀
console.log(`\'` === "'", `\"` === '"'); // true true
console.log(`back\\slash`); // back\slashEscaping a quote inside a template literal is allowed but has no effect, because quotes never needed escaping there.
A backslash at the end of a line is a line continuation. The backslash and the line break are both removed, just as in quoted strings:
const joined = `abc\
def`;
console.log(joined); // abcdef
console.log(joined.length); // 6Without the backslash, the line break would stay in the string. The multiline chapter covers that in detail.
Gotcha: Octal Escapes Are Always Errors
Legacy octal escapes such as \01 and \7 still work in quoted strings in sloppy (non-strict) mode. Template literals have rejected them from the start, in every mode. The one exception is \0 (the null character) when no digit follows it.
// Sloppy-mode function body: the quoted string accepts a legacy octal escape.
const fromQuote = new Function("return '\\01'")();
console.log(fromQuote.length, fromQuote.charCodeAt(0)); // 1 1
// The same escape in a template literal fails to parse.
try {
new Function("return `\\01`");
} catch (e) {
console.log(e.name); // SyntaxError
}
console.log(`\0`.charCodeAt(0)); // 0This rarely matters in new code, but it can break mechanical refactors. If a script turns every '...' in an old codebase into ` ... , it can make files that used to parse fail with a SyntaxError. Sequences like \8 and \9` also fail in untagged templates. The final chapter of this tutorial shows how tagged templates relax these rules.
Where Backtick Literals Are Not Allowed
A template literal can contain substitutions, so the grammar treats it as an expression that needs evaluating, not as a fixed string constant. Several places in JavaScript require a fixed string constant, and they reject backticks even when the template has no ${}.
Object literal keys
// const bad = { `name`: 1 }; // SyntaxError
const good = { [`name`]: 1 }; // computed key: any expression is allowed
console.log(good.name); // 1
try {
new Function("return { `name`: 1 }");
} catch (e) {
console.log(e.name); // SyntaxError
}Square brackets make a computed key, which accepts any expression, including a template literal.
Module specifiers
import x from ./x.js` and export * from ./y.js are both syntax errors. Static imports need a plain quoted string so tools can resolve the dependency graph without running any code. Dynamic import() is an ordinary function-like call, so it does accept a template literal: import(./locale/${lang}.js) ` is valid.
Directives
A "use strict" directive is recognized only when written with single or double quotes. ` use strict ` at the top of a function is just an expression statement with no effect, so the code stays in sloppy mode without any warning.
function looseFn() {
`use strict`;
return this === undefined; // strict mode would make this true
}
function strictFn() {
"use strict";
return this === undefined;
}
console.log(looseFn(), strictFn()); // false trueJSON
JSON is a separate data format, and it accepts only double-quoted strings. JSON.parse('{"a": x}') throws. This affects hand-written config files and API payloads more than JavaScript source.
Gotcha: A Backtick After an Expression Is a Function Call
Any expression placed directly before a template literal turns it into a tagged template. JavaScript calls the expression as a function, and it does so even across a line break. Automatic semicolon insertion (ASI) does not add a semicolon before a line that starts with a backtick, so a missing semicolon can quietly change what the code means:
const greet = (strings) => `tag called with ${JSON.stringify(strings)}`;
const result = greet
`hello`;
console.log(result); // tag called with ["hello"]The author may have meant two separate statements, but the code calls greet with the template's strings. If greet were not a function, the program would throw TypeError: greet is not a function at runtime. Lines that start with ( or [ have the same problem. If you write code without semicolons, put a semicolon in front of any line that begins with a backtick, or turn on a linter rule such as ESLint's no-unexpected-multiline. The tagged templates chapter explains what the tag function receives.
Common Errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `SyntaxError: Unterminated template literal` | Mismatched delimiters, as in `` `hello' ``, or an unescaped backtick inside the text | Match the delimiters, or escape the inner backtick as `` \` `` |
| Output contains a literal `${name}` | The string uses `'` or `"` instead of backticks | Switch the delimiters to backticks |
| `Unexpected template string` in an object literal | A backtick literal used as a key | Use a quoted key or a computed key `` [`k`] `` |
| `SyntaxError` after converting quotes to backticks | A legacy octal escape like `\01` | Replace it with `\x01` or `\u0001` |
| `TypeError: ... is not a function` near a template | Missing semicolon on the line before, so the template became a tag call | Add the semicolon |
| A backtick typed as `'` or `´` | Keyboard layout or smart-quote autocorrect | Use the grave accent key (U+0060) and turn off smart quotes in your editor |
Choosing a Delimiter
Many teams use backticks only when they need interpolation or line breaks, and use single or double quotes everywhere else. This keeps the meaning of each literal clear. A backtick tells the reader to expect something dynamic. Other teams use backticks everywhere for consistency. Modern engines show no measurable performance difference for a template literal without substitutions. Whichever convention you pick, enforce it with a linter, such as ESLint's quotes rule with allowTemplateLiterals, or with Prettier.
Exercises
Exercise
What do these lines print, and why? console.log(typeof x, x === 'x', It's "ok".length)
Show answer
They print: string true 9. An untagged template literal without substitutions produces an ordinary string primitive equal to the same text in quotes. The text It's "ok" has 9 characters, and the quotes inside need no escaping.
Exercise
A developer writes const config = { timeout: 30 }; and gets a SyntaxError. Explain the cause and give two valid rewrites.
Show answer
Object literal keys must be identifiers, quoted strings, numbers, or computed keys. A template literal isn't allowed as a plain key, because the grammar treats it as an expression. Valid rewrites are { timeout: 30 }, { 'timeout': 30 }, and the computed form { [timeout]: 30 }.
Exercise
Without running it, predict the output of: const s = a$b {c} $ {d}; console.log(s.length, s);
Show answer
It prints 13 a$b {c} $ {d}. No $ is immediately followed by {, so the parser starts no substitution, and all 13 characters stay as written.
Exercise
An automated refactor turned var msg = 'Code\07 failed'; into var msg = Code\07 failed; in a sloppy-mode script, and the file no longer loads. Why, and how would you fix it while keeping the same string?
Show answer
\07 is a legacy octal escape. Quoted strings accept it in sloppy mode, but template literals always reject it with a SyntaxError. Replace it with an equivalent escape such as \x07 or \u0007, which both literal forms accept.
Exercise
In semicolon-free code, the line const log = console.log is followed by a line containing only ready. What happens at runtime?
Show answer
ASI inserts no semicolon before a line that starts with a backtick, so the parser reads the two lines as the tagged template console.logready. It calls console.log with the template's strings array and assigns the return value, undefined, to log. The program prints [ 'ready' ] (shown as an array, possibly with its raw property), and log ends up undefined instead of a function.