ES6+ Features: Template Literals
Before ES2015 (ES6), combining variables with strings or creating multi-line strings could be cumbersome. Template Literals (also known as template strings) provide a more powerful and convenient way to handle strings, primarily by offering multi-line string support and string interpolation.
They are defined using backticks (`) instead of single or double quotes.
1. Basic Syntax
The simplest use of a template literal is just a plain string wrapped in backticks. At this point, it behaves just like a regular string.
// Using template literal
const simpleString = `Hello, world!`;
console.log(simpleString); // Output: Hello, world!
// Equivalent to traditional string
const traditionalString = 'Hello, world!';
console.log(traditionalString); // Output: Hello, world!
2. Multi-line Strings
One of the immediate benefits of template literals is the ability to create strings that span multiple lines without needing special escape characters like \n. The line breaks within the backticks are preserved.
// Traditional multi-line string (requires \n)
const traditionalMultiline = 'Line 1\nLine 2\nLine 3';
console.log('--- Traditional Multi-line ---');
console.log(traditionalMultiline);
// Template literal multi-line string (preserves newlines)
// In your JavaScript code, you would write:
// const templateMultiline = `Line A
// Line B
// Line C`;
const templateMultiline = `Line A\nLine B\nLine C`; // For demonstration
console.log('--- Template Literal Multi-line ---');
console.log(templateMultiline);
Output:
--- Traditional Multi-line ---
Line 1
Line 2
Line 3
--- Template Literal Multi-line ---
Line A
Line B
Line C
3. Expression Interpolation
This is where template literals truly shine. You can embed JavaScript expressions directly within a template literal using the syntax ${expression}. The expression inside the curly braces will be evaluated, and its result will be converted to a string and inserted into the final string.
This eliminates the need for messy string concatenation using the + operator.
What can be interpolated?
- Variables:
const name = 'Alice'; const greeting = `Hello, ${name}!`; // "Hello, Alice!" - Function Calls:
function calculateSum(a, b) { return a + b; } const result = `The sum is ${calculateSum(5, 7)}.`; // "The sum is 12." - Arithmetic Operations:
const price = 10; const tax = 2; const total = `Total: $${price + tax}.`; // "Total: $12." - Any Valid JavaScript Expression: Conditional (ternary) operators, array accesses, object property accesses, etc.
const item = 'Laptop';
const quantity = 2;
const unitPrice = 800;
// In your JavaScript code, you would write:
// const orderSummary = `
// Order Details:
// Item: ${item}
// Quantity: ${quantity}
// Unit Price: $${unitPrice}
// Total Cost: $${quantity * unitPrice}
// Status: ${quantity > 0 ? 'In Stock' : 'Out of Stock'}
// `;
const orderSummary = '\n' +
' Order Details:\n' +
' Item: ' + item + '\n' +
' Quantity: ' + quantity + '\n' +
' Unit Price: $' + unitPrice + '\n' +
' Total Cost: $' + (quantity * unitPrice) + '\n' +
' Status: ' + (quantity > 0 ? 'In Stock' : 'Out of Stock') + '\n';
console.log(orderSummary);
4. Nested Template Literals (Brief Mention)
While less common, template literals can be nested. This can be useful for dynamically generating parts of a string that are themselves complex.
const users = ['Alice', 'Bob', 'Charlie'];
// In your JavaScript code, you would write:
// const userList = `Users:
// ${users.map(user => ` - ${user}`).join('\n ')}
// `;
const userList = 'Users:\n' +
' ' + users.map(function(user) { return ' - ' + user; }).join('\n ');
console.log(userList);
5. Tagged Templates (Brief Mention - Advanced)
Template literals also support a more advanced form called "tagged templates." If you place a function name directly before a template literal (without parentheses), that function is called with the raw string parts and the interpolated values. This allows for custom parsing and manipulation of the template literal's output, useful for internationalization, escaping HTML, or domain-specific languages (DSLs).
function highlight(strings, ...values) {
let str = '';
strings.forEach((string, i) => {
str += string;
if (values[i]) {
str += `**${values[i]}**`; // Example: Highlight interpolated values
}
});
return str;
}
const name = 'Maria';
const age = 30;
// In your JavaScript code, you would write:
// const message = highlight`My name is ${name} and I am ${age} years old.`;
// For this environment, we'll demonstrate the *result* of a tagged template.
const message = "My name is **Maria** and I am **30** years old."; // This is the expected output.
console.log(message); // Output: My name is **Maria** and I am **30** years old.
Note: We won't delve deeper into tagged templates in this lesson, but it's good to know they exist.
6. Comparison to Traditional Strings
| Feature | Traditional Strings ('' or "") | Template Literals (`) |
|---|---|---|
| Multi-line | Requires \n for new lines | Supports actual line breaks |
| Interpolation | Requires + concatenation | Uses ${expression} for seamless embedding |
| Escaping Quotes | Need to escape \ for same type of quote | Don't need to escape matching quotes (' in "", " in '') |
Template literals offer a significant improvement in readability and ease of use, making code cleaner and less error-prone when dealing with dynamic or multi-line strings.
Comprehensive Example: Dynamic Greeting Card
Exercise: Generate a User Profile Card
Instructions: Use template literals to create a formatted string representing a user's profile card.
- Declare variables for
firstName,lastName,age,email, andisPremiumUser(boolean). - Create a template literal string named
profileCardthat includes:- The user's full name (
firstNamelastName). - Their age.
- Their email.
- A status line indicating if they are a "Premium User" or "Standard User" based on
isPremiumUser. - Make sure the output is well-formatted with proper line breaks.
- The user's full name (
- Log the
profileCardstring to the console.

