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
- Use backticks — For template literals, not regular quotes
- Use
${}for interpolation — Not string concatenation - Use multi-line — For readability
- Keep expressions simple — Complex logic outside
${} - Combine with
.map()— For dynamic HTML generation
Common Mistakes
- Using regular quotes — Template literals need backticks
- Forgetting
${}— Variables won’t be interpolated - Complex logic inside
${}— Keep it simple - Escaping backticks — Use ``` if you need a literal backtick
- Missing closing backtick — Causes syntax errors