AI Hints
Home›JavaScript Tutorial›Text and Truth
JavaScript · Lesson 10 of 138

Template Literals

Backticks and ${}.

⏱ 2 min read▶ Video at 10:21🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

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.

Template Literals
From the video: Template Literals
  • 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.

app.jsjavascript
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`);
Output
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.

keyvalue
`text`backticks
${value}insert a value
${a * b}any expression
Multi-linejust 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.

app.jsjavascript
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)}`);
Output
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
Next up: String Methods — length, toUpperCase, includes