Learn to create dynamic strings with template literals, use expression interpolation, and build multiline strings with modern ES6 syntax.
Template literals are one of ES6's most practical features, revolutionizing how we work with strings in JavaScript. They replace traditional string concatenation with a more readable, powerful syntax that supports embedded expressions, multiline strings, and advanced formatting.
Beyond simple string interpolation, template literals enable sophisticated templating systems, cleaner code for HTML generation, and more maintainable string-heavy applications. They're essential for modern JavaScript development, especially in frameworks like React where dynamic content generation is common.
In this lesson, you'll master template literal syntax, learn to embed complex expressions, create multiline strings effortlessly, and build dynamic templates that make your JavaScript code more readable and maintainable.
Template literals use backticks (`) instead of quotes and support expression interpolation through ${} syntax. This eliminates the need for complex string concatenation.
1. Basic Template Literal Syntax
1// Traditional string concatenation
2const name = 'Sarah';
3const age = 28;
4const greeting = 'Hello, my name is ' + name + ' and I am ' + age + ' years old.';
5
6// Template literal - much cleaner
7const greeting = `Hello, my name is ${name} and I am ${age} years old.`;
8
9console.log(greeting); // "Hello, my name is Sarah and I am 28 years old."2. Expression Interpolation
1const price = 29.99;
2const tax = 0.08;
3const quantity = 3;
4
5// Complex expressions inside template literals
6const receipt = `
7 Items: ${quantity}
8 Subtotal: $${(price * quantity).toFixed(2)}
9 Tax: $${(price * quantity * tax).toFixed(2)}
10 Total: $${((price * quantity) * (1 + tax)).toFixed(2)}
11`;
12
13console.log(receipt);
14// Items: 3
15// Subtotal: $89.97
16// Tax: $7.20
17// Total: $97.17Template literals naturally support multiline strings without escape characters, making them perfect for HTML templates, SQL queries, and formatted text.
1. Multiline String Creation
1// Traditional multiline strings (awkward)
2const oldHtml = '<div class="card">' +
3 ' <h2>User Profile</h2>' +
4 ' <p>Welcome back!</p>' +
5 '</div>';
6
7// Template literal multiline (natural)
8const newHtml = `
9 <div class="card">
10 <h2>User Profile</h2>
11 <p>Welcome back!</p>
12 </div>
13`;2. Dynamic HTML Generation
1const user = {
2 name: 'Alex Chen',
3 email: '[email protected]',
4 avatar: '/images/alex.jpg',
5 isOnline: true
6};
7
8const userCard = `
9 <div class="user-card ${user.isOnline ? 'online' : 'offline'}">
10 <img src="${user.avatar}" alt="${user.name}" class="avatar">
11 <div class="info">
12 <h3>${user.name}</h3>
13 <p>${user.email}</p>
14 <span class="status">${user.isOnline ? '🟢 Online' : '⚪ Offline'}</span>
15 </div>
16 </div>
17`;
18
19document.getElementById('user-container').innerHTML = userCard;Tagged templates allow you to parse template literals with custom functions, enabling powerful templating systems, internationalization, and specialized string processing.
1. Basic Tagged Template
1// Custom tag function
2function highlight(strings, ...values) {
3 return strings.reduce((result, string, i) => {
4 const value = values[i] ? `<mark>${values[i]}</mark>` : '';
5 return result + string + value;
6 }, '');
7}
8
9const searchTerm = 'JavaScript';
10const description = 'Modern web development';
11
12const highlightedText = highlight`
13 Learn ${searchTerm} for ${description} projects
14`;
15
16console.log(highlightedText);
17// "Learn <mark>JavaScript</mark> for <mark>Modern web development</mark> projects"2. Styled Components Pattern
1// CSS-in-JS with template literals (React style)
2const Button = styled.button`
3 background: ${props => props.primary ? '#007bff' : '#6c757d'};
4 color: white;
5 border: none;
6 padding: ${props => props.size === 'large' ? '12px 24px' : '8px 16px'};
7 border-radius: 4px;
8 font-size: ${props => props.size === 'large' ? '16px' : '14px'};
9 cursor: pointer;
10
11 &:hover {
12 opacity: 0.8;
13 }
14`;
15
16// Usage
17<Button primary size="large">Submit</Button>Create a flexible email template system using template literals for automated customer communications.
1// Email template system with template literals
2class EmailTemplateSystem {
3 constructor() {
4 this.templates = new Map();
5 }
6
7 // Register template with validation
8 registerTemplate(name, template) {
9 if (typeof template !== 'function') {
10 throw new Error('Template must be a function');
11 }
12 this.templates.set(name, template);
13 }
14
15 // Generate email from template
16 generateEmail(templateName, data) {
17 const template = this.templates.get(templateName);
18 if (!template) {
19 throw new Error(`Template '${templateName}' not found`);
20 }
21 return template(data);
22 }
23}
24
25// Initialize system
26const emailSystem = new EmailTemplateSystem();
27
28// Welcome email template
29emailSystem.registerTemplate('welcome', (user) => `
30 <html>
31 <head>
32 <style>
33 .email-container { max-width: 600px; margin: 0 auto; font-family: Arial, sans-serif; }
34 .header { background: #007bff; color: white; padding: 20px; text-align: center; }
35 .content { padding: 20px; }
36 .button { background: #28a745; color: white; padding: 12px 24px; text-decoration: none; border-radius: 5px; display: inline-block; }
37 </style>
38 </head>
39 <body>
40 <div class="email-container">
41 <div class="header">
42 <h1>Welcome to ${user.company}!</h1>
43 </div>
44 <div class="content">
45 <h2>Hello ${user.firstName},</h2>
46 <p>Thank you for joining ${user.company}! We're excited to have you as part of our community.</p>
47
48 <h3>Your Account Details:</h3>
49 <ul>
50 <li><strong>Email:</strong> ${user.email}</li>
51 <li><strong>Member Since:</strong> ${new Date(user.joinDate).toLocaleDateString()}</li>
52 <li><strong>Account Type:</strong> ${user.accountType}</li>
53 </ul>
54
55 <p>To get started, click the button below:</p>
56 <a href="${user.activationUrl}" class="button">Activate Account</a>
57
58 <p>If you have any questions, reply to this email or contact our support team.</p>
59
60 <p>Best regards,<br>The ${user.company} Team</p>
61 </div>
62 </div>
63 </body>
64 </html>
65`);
66
67// Order confirmation template
68emailSystem.registerTemplate('orderConfirmation', (order) => `
69 <html>
70 <body style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
71 <h1>Order Confirmation #${order.id}</h1>
72
73 <h2>Hello ${order.customer.name},</h2>
74 <p>Thank you for your order! Here are the details:</p>
75
76 <div style="border: 1px solid #ddd; padding: 15px; margin: 20px 0;">
77 <h3>Order Items:</h3>
78 ${order.items.map(item => `
79 <div style="display: flex; justify-content: space-between; margin: 10px 0;">
80 <span>${item.name} (x${item.quantity})</span>
81 <span>$${(item.price * item.quantity).toFixed(2)}</span>
82 </div>
83 `).join('')}
84
85 <hr>
86 <div style="display: flex; justify-content: space-between; font-weight: bold;">
87 <span>Total:</span>
88 <span>$${order.total.toFixed(2)}</span>
89 </div>
90 </div>
91
92 <h3>Shipping Information:</h3>
93 <p>
94 ${order.shipping.address}<br>
95 ${order.shipping.city}, ${order.shipping.state} ${order.shipping.zip}<br>
96 Estimated Delivery: ${new Date(order.estimatedDelivery).toLocaleDateString()}
97 </p>
98
99 <p>You can track your order <a href="${order.trackingUrl}">here</a>.</p>
100 </body>
101 </html>
102`);
103
104// Usage examples
105const userData = {
106 firstName: 'Sarah',
107 email: '[email protected]',
108 company: 'TechCorp',
109 joinDate: new Date().toISOString(),
110 accountType: 'Premium',
111 activationUrl: 'https://techcorp.com/activate?token=abc123'
112};
113
114const orderData = {
115 id: 'ORD-2024-001',
116 customer: { name: 'John Smith' },
117 items: [
118 { name: 'Wireless Headphones', quantity: 1, price: 129.99 },
119 { name: 'Phone Case', quantity: 2, price: 24.99 }
120 ],
121 total: 179.97,
122 shipping: {
123 address: '123 Main St',
124 city: 'New York',
125 state: 'NY',
126 zip: '10001'
127 },
128 estimatedDelivery: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString(),
129 trackingUrl: 'https://shipping.com/track/ORD-2024-001'
130};
131
132// Generate emails
133const welcomeEmail = emailSystem.generateEmail('welcome', userData);
134const confirmationEmail = emailSystem.generateEmail('orderConfirmation', orderData);
135
136console.log('Welcome email generated');
137console.log('Order confirmation generated');Your progress is saved in this browser, on this device only.