JavaScript Template Literals
Template literals are strings written with backticks ` instead of quotes. They add three superpowers over ordinary strings: embedded expressions, multi-line text, and tagged templates.
Interpolation with ${…}
Inside a template literal, ${expression} is replaced by the value of the expression. This is called string interpolation, and it's far more readable than chains of +:
const name = "Noor";
const items = 3;
const price = 4.5;
const withPlus = "Hi " + name + ", your " + items + " items cost " + items * price + " EUR.";
const withTemplate = `Hi ${name}, your ${items} items cost ${items * price} EUR.`;
console.log(withPlus);
console.log(withTemplate);Hi Noor, your 3 items cost 13.5 EUR.
Hi Noor, your 3 items cost 13.5 EUR.
Any expression works inside ${}: arithmetic, function calls, method calls, ternaries, even other template literals.
const temp = 23.456;
const user = { first: "Leo", last: "Moreau", admin: true };
console.log(`Temperature: ${temp.toFixed(1)}°C`);
console.log(`Name: ${user.first} ${user.last.toUpperCase()}`);
console.log(`Role: ${user.admin ? "Administrator" : "Member"}`);
console.log(`Initials: ${[user.first, user.last].map((s) => s[0]).join("")}`);Temperature: 23.5°C
Name: Leo MOREAU
Role: Administrator
Initials: LM
Multi-line strings
Line breaks inside backticks are kept as real new lines — no \n needed:
const poem = `Roses are red,
Violets are blue,
Template literals
Are handy for you.`;
console.log(poem);Roses are red,
Violets are blue,
Template literals
Are handy for you.
Be careful: indentation inside the backticks is part of the string too.
Building HTML
Template literals are a natural fit for generating HTML snippets from data. Combined with map and join, a few lines turn an array into a list:
<div id="menu"></div>
<script>
const dishes = [
{ name: "Tomato soup", price: 6 },
{ name: "Pasta", price: 11.5 },
{ name: "Tiramisu", price: 5 },
];
const html = `
<h3>Today's menu</h3>
<ul>
${dishes.map((d) => `<li>${d.name} — <b>${d.price.toFixed(2)} €</b></li>`).join("")}
</ul>`;
document.getElementById("menu").innerHTML = html;
</script>Warning: Only build HTML like this from data you control. Text entered by users must be escaped (or inserted with
textContent) to prevent cross-site scripting.
Escaping inside template literals
To include a literal backtick or ${ in a template literal, escape it with a backslash:
console.log(`Use \`backticks\` for templates`);
console.log(`Write \${expression} to interpolate`);Use `backticks` for templates
Write ${expression} to interpolate
Tagged templates
Put a function name right before a template literal and the function receives the literal's pieces: an array of the fixed strings and the evaluated values. It can return anything. Here a tag highlights every inserted value:
function highlight(strings, ...values) {
return strings.reduce(
(out, str, i) => out + str + (i < values.length ? `[${values[i]}]` : ""),
""
);
}
const city = "Kyoto";
const days = 4;
console.log(highlight`Trip to ${city} for ${days} days`);
console.log(String.raw`C:\new\table`); // built-in tag: no escape processingTrip to [Kyoto] for [4] days
C:\new\table
Tagged templates power libraries for HTML escaping, CSS-in-JS, translations and SQL query builders.
Quotes or backticks?
| Need | Use |
|---|---|
| Plain text with no variables | "…" or '…' (or backticks — all are fine) |
| Values inserted into text | `…${value}…` |
| Text spanning several lines | `…` |
Test yourself
A template literal contains the text 2 + 3 = ${2 + 3} between backticks. What string does it produce?
- "2 + 3 = ${2 + 3}"
- "2 + 3 = 5"
- "2 + 3 = 23"
- An error
Which character delimits a template literal?
- '
- "
- `
- $
In a tagged template (a function name written directly before a template literal), what is the tag's first argument?
- The whole string
- An array of the literal string parts
- The value of x
- A regular expression