Template Literals

Template literals are strings written with backticks. They can embed any expression with ${…}, span multiple lines without escape characters, and even be processed by a function. They've largely replaced + concatenation in modern code.

Interpolation

JS interpolation.js
const name = "Sam";
const items = 3;
const price = 4.5;

console.log("Hi " + name + ", you have " + items + " items.");
console.log(`Hi ${name}, you have ${items} items.`);
console.log(`Total: $${(items * price).toFixed(2)}`);
Output
Hi Sam, you have 3 items.
Hi Sam, you have 3 items.
Total: $13.50

Anything inside ${ } is evaluated as JavaScript and converted to a string: variables, arithmetic, function calls, even ternaries. The $ before ${ in the last line is just a literal dollar sign.

Expressions inside

JS expressions.js
const score = 72;
const user = { first: "Lin", last: "Park" };
const tags = ["js", "web"];

console.log(`Result: ${score >= 50 ? "pass" : "fail"}`);
console.log(`Name: ${user.first} ${user.last.toUpperCase()}`);
console.log(`Tags: ${tags.join(", ")}`);
console.log(`Now: ${new Date(0).toISOString().slice(0, 4)}`);
Output
Result: pass
Name: Lin PARK
Tags: js, web
Now: 1970

Keep interpolations short. If an expression gets complicated, compute it into a well-named variable first.

Multi-line strings

Line breaks inside backticks are kept as-is:

JS multiline.js
const poem = `Roses are red,
Violets are blue,
Template literals
Are handy for you.`;

console.log(poem);
Output
Roses are red,
Violets are blue,
Template literals
Are handy for you.

Be aware that indentation is kept too — if you indent the lines inside your code, those spaces become part of the string.

Building HTML

Template literals make it easy to generate HTML from data:

Try it yourself
Result
Security warning: inserting user-supplied text into HTML this way lets an attacker inject their own markup and scripts — a cross-site scripting (XSS) attack. Only use innerHTML with data you control, or escape it first. For user content, set textContent on elements you create (lesson 43).

Tagged templates

A function name placed directly before a template literal receives the literal's pieces and values separately, and can return anything. This is how libraries implement safe SQL queries, CSS-in-JS and translation:

JS tagged.js
function highlight(strings, ...values) {
  return strings.reduce((out, str, i) => out + str + (i < values.length ? `[${values[i]}]` : ""), "");
}

const item = "coffee";
const qty = 2;
console.log(highlight`Ordered ${qty} cups of ${item}.`);
Output
Ordered [2] cups of [coffee].

strings is the array of literal text parts (["Ordered ", " cups of ", "."]) and values holds the interpolated values. You won't write tag functions often, but you'll recognise them in libraries.

String.raw

The built-in tag String.raw ignores escape sequences — handy for Windows paths and regular expressions:

JS raw.js
console.log(`C:\new\table`.length > 0 ? "escapes processed" : "");
console.log(String.raw`C:\new\table`);
Output
escapes processed
C:\new\table

Try it yourself

Try it yourself
Console output