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
- Using quotes instead of backticks
- Forgetting to use
${}for expressions - Putting complex logic inside template literals (keep it readable)
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
- Template literals use backticks:
`string` - Embed expressions with
${expression} - Support multi-line strings without
\n - Can contain any valid JavaScript expression
- Tagged templates enable advanced string processing
