JS Learning

ES6+ Features

Lesson Progress0%

Section 3 of 4

Template Literals

Template Literals

Topic Overview

Take your time to understand each concept. Practice with the examples below!

Template literals are supercharged strings that make text formatting much easier. Instead of quotes, they use backticks (`) and can do amazing things!

Basic Syntax:

// Old way with quotes:
const name = "Alice";
const greeting = "Hello, " + name + "!";
// New way with template literals:
const greeting = `Hello, ${name}!`;

Key Features:

1. Variable Interpolation (embedding values):
const item = "coffee";
const price = 4.50;
const message = `Your ${item} costs $${price}`;
// "Your coffee costs $4.50"
2. Multi-line Strings (no more \n!):
const poem = `
Roses are red,
Violets are blue,
JavaScript is awesome,
And so are you!

`;

3. Expression Evaluation (math and logic):
const a = 10;
const b = 20;
const result = `${a} + ${b} = ${a + b}`;
// "10 + 20 = 30"
4. Function Calls Inside:
const name = "alice";
const formatted = `Welcome, ${name.toUpperCase()}!`;
// "Welcome, ALICE!"
5. Conditional Logic:
const age = 20;
const status = `You are ${age >= 18 ? 'an adult' : 'a minor'}`;
// "You are an adult"

Real-world examples:

  • Building HTML:`<h1>${title}</h1>`
  • URLs:`https://api.site.com/users/${userId}`
  • Messages:`Hi ${user}, you have ${count} new messages`
  • SQL queries:`SELECT * FROM users WHERE age > ${minAge}`

Why template literals are awesome:

  • Much more readable
  • No more string concatenation mess
  • Easy multi-line text
  • Dynamic content made simple

Ready to practice? Try the exercise below to reinforce your learning!

Try it yourself

Create dynamic strings using template literals with variables and expressions.

Loading...