JavaScript String Templates
Modern way to work with strings using template literals
🎯 What are Template Literals?
Template literals (template strings) are a modern way to create strings in JavaScript. They use backticks (`) instead of quotes and allow embedded expressions and multi-line strings.
// Old way with concatenation
let name = "John";
let greeting = "Hello, " + name + "!";
// New way with template literals
let greeting2 = `Hello, ${name}!`;
console.log(greeting2); // Output: Hello, John!
Template Literal Features
Variable Interpolation
Embed variables directly in strings
`Hello, ${name}!`
Expression Evaluation
Calculate expressions inside strings
`Total: ${price * quantity}`
Multi-line Strings
Create strings spanning multiple lines
`Line 1
Line 2
Line 3`
Function Calls
Call functions inside templates
`Today is ${getDate()}`
🔹 Basic Template Literals
Using backticks and ${} for variable interpolation:
// Variables
let firstName = "Alice";
let lastName = "Johnson";
let age = 25;
// Template literal with variables
let introduction = `Hi, I'm ${firstName} ${lastName} and I'm ${age} years old.`;
console.log(introduction);
// Output: Hi, I'm Alice Johnson and I'm 25 years old.
// Comparison with old concatenation
let oldWay = "Hi, I'm " + firstName + " " + lastName + " and I'm " + age + " years old.";
console.log(oldWay);
// Output: Hi, I'm Alice Johnson and I'm 25 years old.
Output:
Hi, I'm Alice Johnson and I'm 25 years old.
Hi, I'm Alice Johnson and I'm 25 years old.
🔹 Expressions in Templates
You can use any JavaScript expression inside ${}:
// Mathematical expressions
let price = 19.99;
let quantity = 3;
let tax = 0.08;
let receipt = `
Item Price: $${price}
Quantity: ${quantity}
Subtotal: $${price * quantity}
Tax: $${(price * quantity * tax).toFixed(2)}
Total: $${(price * quantity * (1 + tax)).toFixed(2)}
`;
console.log(receipt);
// Conditional expressions
let user = "John";
let isLoggedIn = true;
let message = `Welcome ${isLoggedIn ? user : 'Guest'}!`;
console.log(message); // Output: Welcome John!
Output:
Item Price: $19.99 Quantity: 3 Subtotal: $59.97 Tax: $4.80 Total: $64.77
Welcome John!
🔹 Multi-line Strings
Template literals preserve line breaks and formatting:
// Multi-line string with template literals
let poem = `
Roses are red,
Violets are blue,
JavaScript is awesome,
And so are you!
`;
console.log(poem);
// HTML template
let name = "Sarah";
let htmlTemplate = `
<div class="user-card">
<h2>${name}</h2>
<p>Welcome to our website!</p>
<button>Get Started</button>
</div>
`;
console.log(htmlTemplate);
Output:
Roses are red, Violets are blue, JavaScript is awesome, And so are you!
<div class="user-card">
<h2>Sarah</h2>
<p>Welcome to our website!</p>
<button>Get Started</button>
</div>
🔹 Function Calls in Templates
Call functions directly inside template literals:
// Helper functions
function getCurrentTime() {
return new Date().toLocaleTimeString();
}
function capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
function getRandomNumber() {
return Math.floor(Math.random() * 100) + 1;
}
// Using functions in templates
let userName = "alice";
let status = `
User: ${capitalize(userName)}
Current Time: ${getCurrentTime()}
Lucky Number: ${getRandomNumber()}
Status: ${userName.length > 5 ? 'Long name' : 'Short name'}
`;
console.log(status);
Output:
User: Alice Current Time: 2:30:45 PM Lucky Number: 42 Status: Short name
🔹 Tagged Template Literals
Advanced feature for processing template literals with functions:
// Tagged template function
function highlight(strings, ...values) {
let result = '';
for (let i = 0; i < strings.length; i++) {
result += strings[i];
if (i < values.length) {
result += `<strong>${values[i]}</strong>`;
}
}
return result;
}
// Using tagged template
let product = "Laptop";
let price = 999;
let taggedResult = highlight`The ${product} costs $${price}`;
console.log(taggedResult);
// Output: The <strong>Laptop</strong> costs $<strong>999</strong>
// Simple formatting function
function currency(strings, ...values) {
return strings.reduce((result, string, i) => {
let value = values[i] ? `$${values[i].toFixed(2)}` : '';
return result + string + value;
}, '');
}
let item = "Book";
let cost = 15.5;
let formatted = currency`The ${item} costs ${cost}`;
console.log(formatted); // Output: The Book costs $15.50
Output:
The Laptop costs $ 999
The Book costs $15.50
🔹 Practical Examples
Real-world uses of template literals:
Common Use Cases:
- HTML Generation: Creating dynamic HTML content
- SQL Queries: Building database queries (with caution)
- URLs: Constructing API endpoints
- Messages: User notifications and alerts
- Configuration: Dynamic configuration strings
// API URL construction
let userId = 123;
let apiUrl = `https://api.example.com/users/${userId}/profile`;
// Email template
let customerName = "John Doe";
let orderNumber = "ORD-2024-001";
let emailBody = `
Dear ${customerName},
Thank you for your order ${orderNumber}.
Your order will be processed within 24 hours.
Best regards,
The Team
`;
// CSS generation
let primaryColor = "#3498db";
let cssRule = `
.button {
background-color: ${primaryColor};
border: 2px solid ${primaryColor};
color: white;
}
`;