Advanced JavaScript (ES6+)

Template Literals

13 min Lesson 4 of 40

Template Literals

Template literals (template strings) are one of ES6's most practical features. They provide an elegant way to create strings with embedded expressions, multi-line strings, and even tagged templates for advanced string processing. Let's explore this powerful feature!

Template Literal Syntax with Backticks

Template literals use backticks (`) instead of quotes:

Old Way (String Concatenation): var name = "John"; var greeting = "Hello, " + name + "!"; var message = "Welcome to " + siteName + ", " + name + "!"; New Way (Template Literals): const name = "John"; const greeting = `Hello, ${name}!`; const message = `Welcome to ${siteName}, ${name}!`;
Key Syntax: Template literals use backticks (`) and embed expressions with ${expression} syntax.

String Interpolation with ${}

You can embed any JavaScript expression inside ${}:

Variables: const name = "John"; const age = 25; console.log(`Name: ${name}, Age: ${age}`); // Output: "Name: John, Age: 25" Expressions: const a = 10; const b = 20; console.log(`Sum: ${a + b}`); // "Sum: 30" console.log(`Double: ${a * 2}`); // "Double: 20" console.log(`Is adult: ${age >= 18}`); // "Is adult: true" Function Calls: function getFullName(first, last) { return `${first} ${last}`; } console.log(`Hello, ${getFullName("John", "Doe")}!`); // Output: "Hello, John Doe!" Object Properties: const user = { name: "Jane", age: 30 }; console.log(`User: ${user.name}, Age: ${user.age}`); // Output: "User: Jane, Age: 30"

Complex expressions work seamlessly:

const price = 100; const tax = 0.15; const total = `Total: $${(price * (1 + tax)).toFixed(2)}`; console.log(total); // "Total: $115.00" const items = ["apple", "banana", "orange"]; console.log(`First item: ${items[0]}`); // "First item: apple" console.log(`Item count: ${items.length}`); // "Item count: 3" const condition = true; console.log(`Status: ${condition ? "Active" : "Inactive"}`); // Output: "Status: Active"
Tip: You can embed any valid JavaScript expression inside ${}, including ternary operators, function calls, and calculations.

Multi-Line Strings

Template literals make multi-line strings incredibly easy:

Old Way (Ugly and Error-Prone): var html = "<div>\n" + " <h1>Title</h1>\n" + " <p>Content</p>\n" + "</div>"; New Way (Clean and Readable): const html = ` <div> <h1>Title</h1> <p>Content</p> </div> `;

Multi-line strings preserve formatting:

const message = ` Dear ${name}, Thank you for your order! Order Details: - Product: ${product} - Quantity: ${quantity} - Total: $${total} Best regards, The Team `; console.log(message); // Outputs formatted message with line breaks
Important: Template literals preserve all whitespace, including leading/trailing spaces and line breaks. Trim if needed with .trim().

Tagged Templates

Tagged templates allow you to parse template literals with a function:

Basic Tagged Template: function tag(strings, ...values) { console.log("Strings:", strings); console.log("Values:", values); } const name = "John"; const age = 25; tag`Name: ${name}, Age: ${age}`; // Output: // Strings: ["Name: ", ", Age: ", ""] // Values: ["John", 25]

Practical example - highlighting values:

function highlight(strings, ...values) { return strings.reduce((result, str, i) => { const value = values[i] !== undefined ? `<mark>${values[i]}</mark>` : ''; return result + str + value; }, ''); } const name = "John"; const score = 95; const html = highlight`${name} scored ${score}%`; console.log(html); // Output: "<mark>John</mark> scored <mark>95</mark>%"

Another example - currency formatting:

function currency(strings, ...values) { return strings.reduce((result, str, i) => { const value = values[i] !== undefined ? `$${values[i].toFixed(2)}` : ''; return result + str + value; }, ''); } const price = 19.5; const tax = 2.925; const total = currency`Price: ${price}, Tax: ${tax}`; console.log(total); // Output: "Price: $19.50, Tax: $2.93"

Expression Evaluation in Templates

Expressions are evaluated immediately when the template is created:

let count = 0; const getMessage = () => `Count: ${count++}`; console.log(getMessage()); // "Count: 0" console.log(getMessage()); // "Count: 1" console.log(getMessage()); // "Count: 2" // count is incremented each time

You can use template literals for dynamic content:

const users = [ { name: "John", active: true }, { name: "Jane", active: false }, { name: "Bob", active: true } ]; const userList = users .map(u => `<li class="${u.active ? 'active' : 'inactive'}">${u.name}</li>`) .join(''); const html = ` <ul> ${userList} </ul> `;

HTML Templating with Template Literals

Template literals are perfect for generating HTML:

Simple Card Component: function createCard(title, content, imageUrl) { return ` <div class="card"> <img src="${imageUrl}" alt="${title}"> <h3>${title}</h3> <p>${content}</p> </div> `; } const card = createCard( "Product Name", "Product description goes here", "https://example.com/image.jpg" ); document.getElementById("container").innerHTML = card;

Complex template with nested data:

function createTable(data) { const headers = Object.keys(data[0]); return ` <table> <thead> <tr> ${headers.map(h => `<th>${h}</th>`).join('')} </tr> </thead> <tbody> ${data.map(row => ` <tr> ${headers.map(h => `<td>${row[h]}</td>`).join('')} </tr> `).join('')} </tbody> </table> `; } const users = [ { name: "John", age: 25, city: "New York" }, { name: "Jane", age: 30, city: "London" } ]; const table = createTable(users);
Security Note: Always sanitize user input before inserting into HTML templates to prevent XSS attacks. Never trust user-provided content!

Best Practices and Use Cases

✓ Use Template Literals For: 1. String interpolation (embedding variables) 2. Multi-line strings 3. HTML/XML generation 4. Dynamic messages and notifications 5. URL construction 6. SQL/GraphQL queries (with proper escaping) 7. Logging and debugging messages ✗ Avoid Template Literals When: 1. Simple static strings (use regular strings) 2. User input needs sanitization (use libraries) 3. Performance-critical hot paths (minimal difference)

Practical examples:

URL Construction: const userId = 123; const filter = "active"; const apiUrl = `https://api.example.com/users/${userId}?status=${filter}`; SQL Query (with proper escaping): const id = 42; const query = `SELECT * FROM users WHERE id = ${id}`; // Note: Use parameterized queries in production! Error Messages: const errorMessage = ` Error: Failed to load user data User ID: ${userId} Timestamp: ${new Date().toISOString()} Please try again later. `; Console Logging: console.log(`User ${user.name} (${user.email}) logged in at ${timestamp}`);

Practice Exercise:

Refactor this code to use template literals:

var firstName = "John"; var lastName = "Doe"; var age = 25; var fullName = firstName + " " + lastName; var intro = "Hello, my name is " + fullName + " and I am " + age + " years old."; var html = "<div class=\"user\">\n" + " <h2>" + fullName + "</h2>\n" + " <p>Age: " + age + "</p>\n" + "</div>";

Solution:

const firstName = "John"; const lastName = "Doe"; const age = 25; const fullName = `${firstName} ${lastName}`; const intro = `Hello, my name is ${fullName} and I am ${age} years old.`; const html = ` <div class="user"> <h2>${fullName}</h2> <p>Age: ${age}</p> </div> `;

Real-World Application

Email Template Generator: function generateEmail(recipient, order) { return ` Hi ${recipient.name}, Thank you for your order #${order.id}! ${order.items.map(item => ` - ${item.name} x${item.quantity}: $${item.price * item.quantity} `).join('')} Total: $${order.total} Expected delivery: ${order.deliveryDate} Questions? Reply to this email. Best regards, ${order.storeName} `.trim(); } const email = generateEmail( { name: "John" }, { id: 12345, items: [ { name: "Laptop", quantity: 1, price: 999 }, { name: "Mouse", quantity: 2, price: 25 } ], total: 1049, deliveryDate: "Dec 15, 2024", storeName: "TechStore" } );

Summary

In this lesson, you learned:

  • Template literals use backticks (`) for string creation
  • ${expression} embeds any JavaScript expression
  • Multi-line strings preserve formatting without escape characters
  • Tagged templates enable custom string processing
  • Perfect for HTML generation and string interpolation
  • More readable than string concatenation
  • Always sanitize user input when generating HTML
Next Up: In the next lesson, we'll explore destructuring - a powerful way to extract values from arrays and objects with clean, concise syntax!

ES
Edrees Salih
10 hours ago

We are still cooking the magic in the way!