Strings
Template literals `…${}…`
A string with "slots" where values are filled in.
Why it exists
Almost every piece of text on screen is a template with data: "Hi, Ann!", "Order #42, $15 total", "3 days left". Joining with + is awkward for this: it's easy to forget a space or a quote, and "Total: " + a + " for " + b + " items" is hard to read. A template literal looks almost like the final text — you see right away where each value goes.
Where it's used
- Messages to the user:
`Hi, ${user.name}!`. - Request URLs:
`/api/users/${id}/orders`. - Markup and multi-line text: emails, HTML templates.
- Debugging:
console.log(`x = ${x}, y = ${y}`).
Syntax
`text ${expression} text`Examples
const name = "Ann";
const items = 3;
`Hi, ${name}! Items in cart: ${items}`; // → "Hi, Ann! Items in cart: 3"const price = 12;
const count = 3;
`Total: $${price * count}`; // → "Total: $36"${}const count = 1;
`${count} ${count === 1 ? "item" : "items"}`; // → "1 item"const text = `Line 1
Line 2`;
text.split("\n").length; // → 2Results after // → aren't just written down — an automatic check runs and verifies them before every site update.
Why it works this way
Inside ${…} you can put any expression: a variable, arithmetic, a function call, a ternary. JavaScript evaluates it and turns the result into a string — just as joining with + does.
Line breaks inside backticks are kept as they are, so multi-line text needs no \n.
Template literals arrived in 2015 (ES6). Before that, everything was built with +, which is why old code is full of joining.
The backtick ` is usually on the key to the left of 1, under Esc.
Traps
How it differs from…
- Joining strings
+does the same thing, only longer, and it's easy to lose a space. For one or two pieces+is fine; for a template with several values, backticks are better.
When to pick something else
For a string with no substitutions, ordinary quotes are simpler. And for big markup templates (emails, pages), components or template engines are better — they escape the data for you.