~/
JavaScript Template Literals
Quiz
...

JavaScript Template Literals

beginner · updated Tue Sep 08 2026Contribute

Master JavaScript template literals to create dynamic strings with ease using interpolation and multi-line formatting for cleaner, more readable code.

JavaScript Template Literals

Template literals use backticks instead of quotes, making strings cleaner and more readable.

Basic Interpolation

// Old way
let message = "Hello, " + name + "!";

// Template literal
let message = `Hello, ${name}!`;

Use ${} to embed any expression inside a string:

let age = 30;
let info = `You are ${age} years old.`;
let next = `Next year you'll be ${age + 1}.`;

Multi-line Strings

// Old way
let msg = "Line 1\nLine 2\nLine 3";

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

No need for \n — just press Enter.

Expressions in ${}

let price = 10;
let quantity = 3;
let total = `Total: $${price * quantity}`;

let items = ["apple", "banana", "orange"];
let list = `Fruits: ${items.join(", ")}`;

Tip: Keep expressions simple. Complex logic belongs outside ${}.

Generating HTML

let users = ["Alice", "Bob", "Charlie"];

let html = `<ul>
${users.map(user => `  <li>${user}</li>`).join("\n")}
</ul>`;

Complete Example: User Card

let name = "Alice";
let age = 30;
let city = "New York";

let card = `
Name:  ${name}
Age:   ${age}
City:  ${city}
-------------------`;

console.log(card);

Best Practices

  1. Use backticks — For template literals, not regular quotes
  2. Use ${} for interpolation — Not string concatenation
  3. Use multi-line — For readability
  4. Keep expressions simple — Complex logic outside ${}
  5. Combine with .map() — For dynamic HTML generation

Common Mistakes

  1. Using regular quotes — Template literals need backticks
  2. Forgetting ${} — Variables won’t be interpolated
  3. Complex logic inside ${} — Keep it simple
  4. Escaping backticks — Use ``` if you need a literal backtick
  5. Missing closing backtick — Causes syntax errors