Curriculum / Intermediate / Lesson 17

Template Literals

String interpolation, multi-line strings, and tagged templates.

17 of 30
intermediate 📖 4 min read 🎯 3 questions

What are Template Literals?

Template literals are a way to work with strings that allow embedded expressions and multi-line strings. They use backticks (`) instead of quotes.

💡 Key insight Template literals use ${} syntax for embedding expressions — much cleaner than string concatenation.

String Interpolation

let name = "Alice";
let age = 25;

// Old way (concatenation)
let message1 = "Hello, " + name + "! You are " + age + " years old.";

// Template literal
let message2 = `Hello, ${name}! You are ${age} years old.`;

Multi-line Strings

// Old way (with \n)
let multi1 = "Line 1\nLine 2\nLine 3";

// Template literal
let multi2 = `Line 1
Line 2
Line 3`;

Expressions in Template Literals

You can put any valid JavaScript expression inside ${}.

let a = 5;
let b = 10;
let result = `The sum of ${a} and ${b} is ${a + b}.`;
// "The sum of 5 and 10 is 15."

Tagged Templates

A more advanced feature where a function processes the template literal.

function highlight(strings, ...values) {
  return strings.reduce((result, str, i) => {
    return result + str + (values[i] ? `${values[i]}` : '');
  }, '');
}

let name = "Alice";
let tag = highlight`Hello, ${name}!`;
// "Hello, Alice!"

Common Mistakes

Quick Quiz

1. What delimiter do template literals use?

2. How do you embed an expression in a template literal?

3. Can template literals be multi-line?

Summary

Back to curriculum