Template Literals
Backticks and ${}.
Joining strings with plus gets messy fast, with all those quotes and spaces. Modern JavaScript has a much nicer way. Template literals, written with backticks instead of quotes.

- Plus gets messy
- A nicer way
- Backticks
Dollar and braces
Inside backticks, dollar sign and curly braces drop a value straight into the text. You can even put a calculation inside. And a template literal can span several lines, exactly as you type it. Run it.
const name = "Ana";
const items = 3;
const price = 4.5;
console.log(`Hi ${name}, you have ${items} items.`);
console.log(`Total: $${(items * price).toFixed(2)}`);
console.log(`Line one
Line two`);Hi Ana, you have 3 items. Total: $13.50 Line one Line two
Use them often
Template literals are easier to read, and harder to get wrong. Most modern JavaScript uses them whenever text includes a value. The backtick key is usually at the top left of your keyboard, below Escape. Plain quotes are still fine for simple text with no values.
| key | value |
|---|---|
| `text` | backticks |
| ${value} | insert a value |
| ${a * b} | any expression |
| Multi-line | just press enter |
Building a receipt
Template literals shine when you build bigger pieces of text. Here we build a little receipt from variables. Each line uses dollar and braces for the values, and to fixed keeps two decimal places. Pad end adds spaces, so the prices line up in a column. Run it.
const item = "Coffee";
const qty = 2;
const price = 3.2;
console.log(`${item.padEnd(10)} x${qty} $${(qty * price).toFixed(2)}`);
console.log(`${"Cake".padEnd(10)} x1 $${(4).toFixed(2)}`);
console.log(`${"Total".padEnd(14)} $${(qty * price + 4).toFixed(2)}`);Coffee x2 $6.40 Cake x1 $4.00 Total $10.40
Summary
Template literals use backticks, and dollar braces to insert values. They're the cleanest way to build text. Next, useful string methods.
Key takeaways- `Hi ${name}`
- Expressions inside
- Multi-line text