Template literals
A backtick string is a template literal, and it does two things that the other two quote styles cannot: it puts the value of an expression into the text with ${}, and it keeps the newlines and the indentation that are written inside it. Both are part of the literal, so the text a reader sees in the source is the text the program builds.
The third feature is the tag: a function written before the literal receives the literal parts and the values separately, which is how a library escapes a value for HTML or builds a query. This lesson shows the interpolation, the multi-line text, one tagged template and the raw form that keeps a backslash as it was typed. It replaces most of the concatenation of the lesson before the last.
Interpolation
Everything between ${ and } is an expression: a name, a call, an arithmetic operation or a conditional. The result is converted to text with the same rules as the plus sign, so a number prints with its digits and an object prints as [object Object]. A literal can hold as many of them as it needs.
const name = 'Ada';
const items = 3;
const price = 19.9;
const total = items * price;
console.log(`Hello, ${name}`);
console.log(`${items} items at ${price.toFixed(2)}`);
console.log(`total: ${total.toFixed(2)}`);
console.log(`kind: ${items > 1 ? 'several' : 'one'}`);
console.log(`arithmetic: ${2 + 3}`);
console.log(`an object: ${{ id: 1 }}`);
node interpolation.js
Hello, Ada
3 items at 19.90
total: 59.70
kind: several
arithmetic: 5
an object: [object Object]
The expression is evaluated before the text is assembled, which is why ${2 + 3} prints five rather than the three characters of the sum. The object line is the one to watch: the default conversion is not JSON, and a program that wants the braces has to call JSON.stringify inside the placeholder. The old form of the first line was 'Hello, ' + name, and the literal is easier to read once a line has more than one value in it.
Multi-line text
A newline inside the literal is a newline in the value, and the indentation travels with it. That makes a block of text readable in the source and awkward in a function, where the literal sits inside an indented body and every line keeps the indentation of the call. The program prints the text and then counts its lines and its length.
const address = `Ada Lovelace
12 St James's Square
London`;
console.log(address);
console.log('lines:', address.split('\n').length);
console.log('length:', address.length);
const indented = `one
two
three`;
console.log(indented);
console.log('second line:', indented.split('\n')[1]);
node multiline.js
Ada Lovelace
12 St James's Square
London
lines: 3
length: 40
one
two
three
second line: two
The value has three lines and the newlines are counted in the length, so the number is larger than the visible characters. The indented literal shows the cost: the spaces in front of two and three are part of the value. A program that needs unindented text builds it from lines and joins them, or trims the value after the fact, which is the operation trim does at the ends only.
A tagged template
A tag is a function placed directly before the literal, with no parentheses. It receives the fixed parts as an array and the values as the remaining arguments, so it can decide how each value is written. The one below wraps every value in brackets, which is the smallest version of what a library does when it escapes a value for HTML. The array of fixed parts has one element more than the values, because it also holds the text after the last placeholder.
function highlight(strings, ...values) {
return strings.reduce((text, part, index) => {
const value = index < values.length ? `[${values[index]}]` : '';
return text + part + value;
}, '');
}
const user = 'ada';
const role = 'admin';
console.log(highlight`user ${user} is ${role}`);
function countParts(strings) {
return strings.length;
}
console.log('typeof the tag:', typeof highlight);
console.log('parts:', countParts`a${1}b${2}c`);
node tagged.js
user [ada] is [admin]
typeof the tag: function
parts: 3
The tag returned a string, and it could have returned anything: a node of a tree, a query object or an escaped piece of HTML. The number of parts is the number of values plus one, which is the invariant a tag relies on. A tag that wants the raw text of a part reads it from strings.raw, which is what the next section uses.
Escapes and String.raw
The escape sequences of a normal string work in a literal too, and String.raw is a tag that keeps them as they were typed. That is what a Windows path or a regular expression needs: a backslash that stands for itself without being doubled in the source. The two forms are printed on the same text so the difference is visible.
console.log(`one\ntwo`);
console.log(String.raw`one\ntwo`);
console.log(`backslash: \\`);
console.log(String.raw`backslash: \\`);
console.log(`two plus two: ${2 + 2}`);
console.log(String.raw`two plus two: ${2 + 2}`);
console.log(String.raw`a path: C:\temp`);
node escapes.js
one
two
one\ntwo
backslash: \
backslash: \
two plus two: 4
two plus two: 4
a path: C:\temp
The first two lines are the same source text and two different values: the escape became a newline in the first and stayed as a backslash and an n in the second. Interpolation still works inside a raw template, so the value of an expression is written normally while the fixed parts stay raw. The path is the case that makes the tag worth knowing, and the next lesson uses it for a pattern.
Exercises
- Put a function call inside a placeholder in interpolation.js, as in ${name.toUpperCase()}. Which value arrives?
- Print 'Hello, ${name}' with single quotes. What does the output show, and why is the placeholder not replaced?
- Build a literal with a tab escape and print its length. How many characters does the value have, and what does the output look like?
- Add a third value to the tagged template in tagged.js. How do the parts and the values line up, and what does the output show?
- Print a backslash with String.raw and without it. Which of the two keeps the doubled backslash as two characters?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does this program print? ``
const n = 2; console.log(n is ${n});``Answer
n is 2
The placeholder is replaced by the value of the expression inside it.
-
What does this program print? ``
console.log(sum: ${2 + 3});``Answer
sum: 5
The expression is evaluated before the text is assembled, so the addition happens first.
-
What does a newline inside a template literal become?
Answer
A newline in the value
The literal keeps the newlines and the indentation that are written inside it.
-
What does this program print? ``
const o = { id: 1 }; console.log(${o});``Answer
[object Object]
The default conversion of an object is the tag [object Object], and JSON needs an explicit call.
-
What does a tag receive as its first argument?
Answer
An array of the fixed text parts
The fixed parts come first as an array, and the values follow as separate arguments.
-
How many parts does a tag get for a literal with two placeholders?
Answer
3
The parts are the text before the first, between the two and after the last, so there is one more than the values.
-
What does this program print? ``
console.log(String.rawa\nb.length);``Answer
4
The raw string keeps the backslash and the n as two characters, so the value has four.
-
Which problem does
String.rawsolve?Answer
A backslash that must stay a backslash without being doubled
The tag keeps the escape sequences as typed, which is what a path or a pattern needs.
-
What does this program print? ``
console.log(a b.length);``Answer
3
The space between the two letters is part of the value, so the length is three.
-
What is
typeofof the result of a tag that returns a string?Answer
string
The tag is a function, and the type of its return value is whatever the function returns.
The code on this page was run with Node.js 24.22.1 and linted with ESLint 10.14.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev