Template Literals
Learn modern string formatting with JavaScript template literals.
Template literals, introduced in ES6, revolutionized how we work with strings in JavaScript. Using backticks instead of quotes, they allow embedded expressions, multi-line strings, and cleaner string formatting. This modern approach eliminates the need for awkward string concatenation and makes your code more readable.
📚 Concepts & Theory
Basic Template Literal:
const name = "Alice";
const greeting = Hello, ${name}!;
// Result: "Hello, Alice!"
Expressions Inside:
const price = 19.99;
const tax = 0.1;
const message = Total: $${price * (1 + tax)};
// Result: "Total: $21.989"
Multi-line Strings:
const html = `
<div>
<h1>Welcome</h1>
<p>This is a paragraph</p>
</div>
`;
Comparison with Concatenation:
// Old way (concatenation)
const old = "Hello, " + name + "! You have " + count + " items.";
// New way (template literal)
const new = Hello, ${name}! You have ${count} items.;
When to Use:
- Use template literals for any string with variables
- Use them for multi-line strings
- Use regular quotes for simple static strings
🎯 Your Challenge
Create a template literal called `message` that says "Welcome, [name]! You have [items] items in your cart." where name = "Sarah" and items = 3.
📝 Starter Code
// Variables
const name = "Sarah";
const items = 3;
// Create message using template literal
const message =
- Template literals use backticks ` not quotes
- Embed variables with ${variable}
- No + operators needed inside
- The backtick is usually on the key with tilde ~
Solution
const name = "Sarah";
const items = 3;
const message = `Welcome, ${name}! You have ${items} items in your cart.`;
Explanation
We use backticks (`) instead of regular quotes to create a template literal. Variables are embedded using ${variableName} syntax. This is cleaner than concatenating multiple strings with + operators.
⚠️ Common Mistakes to Avoid
- Using regular quotes instead of backticks
- Forgetting the $ before curly braces
- Using + inside template literals unnecessarily
- Mixing template syntax with concatenation