JavaScript Template Literals: Interpolation, Multi-line Strings, Tagged Templates and String.raw
Backtick strings in depth: ${} interpolation and how values become text, multi-line strings and the indentation problem, nesting, tagged templates (what the tag receives, raw strings, caching), String.raw, and real tags for HTML escaping, SQL parameters and dedenting.
kvi5hnuCode Sprout team member6 min readOn this page
Template literals, the strings written with backticks, arrived in ES2015 and quickly became the most common way to build strings. They do three things ordinary quotes can't: embed expressions with ${...}, span multiple lines, and pass their pieces to a function (a tag) that can process them any way it likes. That last feature powers libraries such as lit, styled-components and many SQL clients.
Interpolation
Anything inside ${ and } is a JavaScript expression: it's evaluated, converted to a string and inserted.
const user = { name: "Ana", unread: 3 };
const price = 4.5, qty = 3;
console.log(`Hi ${user.name}, you have ${user.unread} new messages`);
console.log(`Total: ${(price * qty).toFixed(2)}`); // any expression
console.log(`You have ${user.unread === 1 ? "1 message" : `${user.unread} messages`}`); // nested template
console.log(`Today is ${new Date(0).toISOString().slice(0, 10)}`);
Hi Ana, you have 3 new messages
Total: 13.50
You have 3 messages
Today is 1970-01-01
Compare with concatenation, "Hi " + user.name + ", you have " + user.unread + " new messages": the template is easier to read and harder to get wrong (no forgotten spaces).
Only expressions are allowed, not statements: ${if (x) ...} is a syntax error; use the conditional operator ?: instead. A literal ${ is written \${, and a literal backtick \`.
How values become text
Each value is converted with the same rules as String(value):
console.log(`${null} ${undefined} ${true} ${42n}`);
console.log(`${[1, 2, [3, 4]]}`); // arrays join with commas
console.log(`${{ a: 1 }}`); // plain objects aren't useful
console.log(`${JSON.stringify({ a: 1 })}`); // so serialize them yourself
const temperature = {
valueOf() { return 21.5; },
toString() { return "21.5 °C"; },
};
console.log(`${temperature}`, "" + temperature); // template prefers toString
try {
console.log(`${Symbol("id")}`);
} catch (err) {
console.log(err.name); // symbols refuse implicit conversion
}
null undefined true 42
1,2,3,4
[object Object]
{"a":1}
21.5 °C 21.5
TypeError
Notice the difference from +: a template converts with the "string" preference, so it calls toString first, while "" + value uses the "default" preference, which for most objects calls valueOf first. Article 24 explains these conversion rules. The visible [object Object] in a UI is a classic bug that comes from interpolating an object.
Multi-line strings
Line breaks inside backticks are part of the string, exactly as typed, and so is every space of indentation:
function help() {
return `Usage:
app run start the server
app test run the tests`;
}
console.log(help());
console.log(JSON.stringify(help().split("\n")[1]));
Usage:
app run start the server
app test run the tests
" app run start the server"
That's sometimes what you want and sometimes not. Common solutions: keep the text at the left margin, build it from an array with join("\n"), or write a small dedent tag (shown below). Line endings in the source are normalized: even if the file has Windows \r\n line endings, a template contains just \n.
Tagged templates
Put a function name right before a template, and JavaScript calls the function with the template's pieces instead of building a string:

function inspect(strings, ...values) {
console.log("strings:", strings);
console.log("values: ", values);
return "anything";
}
const name = "Ana", count = 3;
const result = inspect`Hi ${name}, you have ${count} new messages`;
console.log(result);
inspect`${name}`; // pieces can be empty strings
strings: [ 'Hi ', ', you have ', ' new messages' ]
values: [ 'Ana', 3 ]
anything
strings: [ '', '' ]
values: [ 'Ana' ]
Rules worth knowing:
strings.lengthis alwaysvalues.length + 1, so text and values alternate:strings[0],values[0],strings[1],values[1], ...,strings[n].- The values arrive unconverted: numbers, objects and functions, exactly as the expressions produced them. The tag decides what to do with them.
- The tag can return anything, not just a string.
- There are no parentheses:
tag`...`is the call. Anything that evaluates to a function works as a tag, such asobj.method`...`ormakeTag(options)`...`.
A tag that escapes HTML
Inserting user data into HTML with a plain template is how cross-site scripting (XSS) attacks happen. A tag can escape every value automatically while leaving your own markup alone:
const escapeHtml = value =>
String(value)
.replaceAll("&", "&")
.replaceAll("<", "<")
.replaceAll(">", ">")
.replaceAll('"', """)
.replaceAll("'", "'");
function html(strings, ...values) {
return strings.reduce((out, text, i) => out + escapeHtml(values[i - 1]) + text);
}
const comment = '<img src=x onerror="alert(1)">';
console.log(html`<p class="comment">${comment}</p>`);
<p class="comment"><img src=x onerror="alert(1)"></p>
The reduce without an initial value starts with strings[0] and, for each later piece, adds the escaped value before it. This interleaving pattern is the core of almost every tag.
A tag that builds SQL parameters
Database libraries use tags to make SQL injection impossible: values never become part of the SQL text, they're sent separately as parameters.
function sql(strings, ...values) {
const text = strings.reduce((query, piece, i) => `${query}$${i}${piece}`);
return { text, values };
}
const email = "ana@example.com' OR '1'='1";
const query = sql`SELECT * FROM users WHERE email = ${email} AND active = ${true}`;
console.log(query.text);
console.log(query.values);
SELECT * FROM users WHERE email = $1 AND active = $2
[ "ana@example.com' OR '1'='1", true ]
The tag returns an object, not a string. The malicious input stays a harmless parameter value. (The $${i} produces a literal $ followed by the number: $ is ordinary text unless followed by {.)
A dedent tag
function dedent(strings, ...values) {
const full = strings.reduce((out, text, i) => out + values[i - 1] + text);
const lines = full.replace(/^\n/, "").replace(/\n\s*$/, "").split("\n");
const indent = Math.min(...lines.filter(l => l.trim()).map(l => l.match(/^ */)[0].length));
return lines.map(l => l.slice(indent)).join("\n");
}
const port = 8080;
const message = dedent`
Server started
port: ${port}
mode: development
`;
console.log(message);
Server started
port: 8080
mode: development
Packages such as dedent and common-tags offer polished versions of this and other text-formatting tags.
Raw strings and String.raw
The strings array has an extra property, raw, with the text as written in the source, before escape sequences are processed:
function show(strings) {
return { cooked: strings[0], raw: strings.raw[0] };
}
console.log(show`tab:\t newline:\n`);
{ cooked: 'tab:\t newline:\n', raw: 'tab:\\t newline:\\n' }
The built-in tag String.raw uses the raw text, so backslashes are kept as they are. That's handy for Windows paths, regex sources and LaTeX:
console.log(String.raw`C:\new\table`); // \n and \t are not escapes here
console.log(`C:\\new\\table`); // the same thing, with doubling
console.log(String.raw`\d+ items: ${2 + 3}`); // interpolation still works
const digits = new RegExp(String.raw`^\d{3}-\d{4}$`);
console.log(digits.test("555-0199"));
C:\new\table
C:\new\table
\d+ items: 5
true
One limitation: String.raw can't end with an odd number of backslashes, because \` would escape the closing backtick.
A tagged template may contain escape sequences that would be errors in a normal string, such as \unicode (since ES2018). The tag gets undefined for that cooked piece, but the raw text is available. This lets tags implement mini-languages like LaTeX, where \u means something else.
Caching: the strings array is per call site
For a given template in your source code, the engine creates the strings array once and passes the same frozen array every time that code runs:
const identity = strings => strings;
const sameSite = () => identity`hello ${0}`;
console.log(sameSite() === sameSite()); // the same call site: same array
console.log(identity`hello ${0}` === identity`hello ${0}`); // different sites: different arrays
console.log(Object.isFrozen(sameSite()));
true
false
true
Libraries use this as a cache key. lit, for example, parses each HTML template once, keyed by its strings array, and on later renders only updates the values, which is a large part of why it's fast.
Common questions
Are template literals slower than concatenation?
No meaningful difference in modern engines; both compile to similar code. Choose for readability.
Can I store a template in a variable and fill it in later?
Not directly: a template is evaluated immediately where it's written. Wrap it in a function: const greet = name => `Hello ${name}`, then call greet("Ana"). For templates loaded from files or translations, use a templating or message-formatting library (for example one based on ICU MessageFormat), never eval.
Can I use template literals as object keys or in imports?
As computed keys, yes: { [`key_${i}`]: value }. But a template with ${} can't be used where the language requires a fixed string, such as the source in import ... from "..." or a "use strict" directive.
Why is my JSON in a template showing [object Object]?
Interpolation converts objects with String(), which gives "[object Object]". Insert JSON.stringify(obj) instead.
Summary
- Backticks allow
${expression}interpolation; values are converted likeString(value)(preferringtoString), and symbols throw. - Line breaks and indentation inside backticks are kept literally; dedent with a tag or keep text at the margin.
tag`...`callstag(strings, ...values):stringshas one more item thanvalues, values arrive unconverted, and the tag can return anything.- Tags enable safe HTML, parameterized SQL, CSS-in-JS, dedenting and more.
strings.rawholds unprocessed text;String.rawkeeps backslashes, which suits paths and regexes.- The
stringsarray is frozen and reused for each call site, so libraries can cache by it.
Practice Questions
What does `${1}${2}` + 3 evaluate to?
Answer
"123". The template produces the string "12", and + with a string concatenates.
In tag`a${x}b${y}`, what are strings and values?
Answer
strings is ["a", "b", ""] and values is [x, y]. The final piece is the empty text after ${y}.
Write a tag upper that uppercases every interpolated value but leaves the literal text unchanged.
Answer
const upper = (s, ...v) => s.reduce((out, t, i) => out + String(v[i - 1]).toUpperCase() + t);
Then upper`hi ${"ana"}!` is "hi ANA!".
What does String.raw`a\nb`.length return?
Answer
4: the characters a, backslash, n and b. Without String.raw, the length would be 3.
Why might a UI show "Welcome, undefined"?
Answer
The interpolated expression evaluated to undefined, often a misspelled property (user.fullname instead of user.fullName) or data that hasn't loaded yet. Templates convert undefined to the text "undefined" instead of throwing, so check the data or use a fallback: ${user.name ?? "guest"}.
Previous: JavaScript String Methods: Searching, Slicing, Replacing, Padding and More
Next: JavaScript Booleans: true, false, Truthy and Falsy Values

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.