JavaScript Beginner Language Basics · 6 min read

Template Literals

Lesson 35 of 38 in the JavaScript learning path.

How do I build a sentence from a title and a seat count?

A template literal is a backtick string that interpolates expressions with ${}.

Concatenation drops spaces and gets unreadable. A template keeps the sentence in one place.

Syntax & Parameters

Syntax
const line = `${lesson.title} has ${lesson.seats} seats`;

Example

Interactive preview available
label.js
const lesson = { title: "Routes", seats: 20, track: "php" };
const line = `${lesson.title} (${lesson.track}) has ${lesson.seats} seats`;
const item = document.createElement("p");
item.textContent = line;
document.body.append(item);
const html = `<p>${lesson.title}</p>`;
const box = document.querySelector("#note");
const size = html.length;
if (box) {
  box.textContent = "built " + size + " chars";
}
const same = line.includes(lesson.title);

Expected Output

A paragraph reading Routes (php) has 20 seats.

Line-by-Line Walkthrough

  1. Backticks open the template.
  2. Each ${} inserts the expression value.
  3. The result is one string.
  4. textContent assigns it so tags in a title cannot run.
  5. A second template shows a markup string.
  6. That markup is not assigned with innerHTML.
  7. The length is only a demonstration.
  8. Never drop a user title into innerHTML through a template.

Common Pitfalls & Security

Read the limits before you copy this.

  • A template assigned to innerHTML is an XSS hole if it includes user text.
  • A missing backtick turns the next lines into code and confuses the parser.
  • Nested templates are hard to read. Build the inner value first.
  • Whitespace inside the backticks is part of the string.

Best Practices & Modern Standards

Use templates for sentences and textContent for insertion.

If you must build HTML, escape first or use createElement.

Real-World Use

The enrollment receipt line is one template: the lesson title, the track, and the seat count.

Frequently Asked Questions

Can I put any expression inside ${}?

Yes. A call or a ternary is fine. Keep it short.

Do templates escape HTML?

No. They only build a string. You choose how it is inserted.

Can they span lines?

Yes. Newlines inside backticks are kept.

What is a tagged template?

A function placed before the backticks receives the parts. Use that for a sanitizer, not for everyday labels.

Need more coins?

You do not have enough coins for this action.

Your balance: 0 coins

Share

Reactions

Loading reactions…