JavaScript Template Literals
Introduction
Template literals (introduced in ES6/ES2015) represent a modern approach to working with strings in JavaScript. They provide an elegant solution to common string manipulation challenges and offer several advantages over traditional string concatenation.
Before template literals, creating complex strings with dynamic content or spanning multiple lines was cumbersome and error-prone. Template literals solve these issues by allowing you to embed expressions directly within strings and easily create multi-line content.
In this guide, we'll explore how template literals work, when to use them, and how they can improve your JavaScript code.
Basic Syntax
Template literals are enclosed by backticks (`
) instead of single or double quotes.
// Traditional string
const traditionalString = "Hello, world!";
// Template literal
const templateLiteral = `Hello, world!`;
console.log(templateLiteral); // Output: Hello, world!
While this basic usage looks similar to regular strings, template literals offer much more flexibility.
String Interpolation
One of the most powerful features of template literals is string interpolation - the ability to embed expressions directly within strings using ${expression}
syntax.
const name = "Sarah";
const age = 28;
// Traditional string concatenation
const greeting1 = "Hello, my name is " + name + " and I am " + age + " years old.";
// Using template literals
const greeting2 = `Hello, my name is ${name} and I am ${age} years old.`;
console.log(greeting2); // Output: Hello, my name is Sarah and I am 28 years old.
You can include any valid JavaScript expression inside ${}
:
const a = 5;
const b = 10;
console.log(`Sum: ${a + b}`); // Output: Sum: 15
console.log(`${a} is ${a > b ? "greater than" : "less than"} ${b}`); // Output: 5 is less than 10
Multi-line Strings
Template literals preserve line breaks and indentation, making multi-line strings much easier to work with:
// Traditional multi-line strings (messy and error-prone)
const multiline1 = "This is line 1\n" +
"This is line 2\n" +
"This is line 3";
// Using template literals
const multiline2 = `This is line 1
This is line 2
This is line 3`;
console.log(multiline2);
// Output:
// This is line 1
// This is line 2
// This is line 3
This makes template literals perfect for creating HTML templates or other content with complex formatting.
Nesting Template Literals
You can nest template literals within each other:
const person = {
name: "Alex",
hobbies: ["coding", "reading", "hiking"]
};
const bio = `
<div class="profile">
<h2>${person.name}</h2>
<p>Hobbies:</p>
<ul>
${person.hobbies.map(hobby => `<li>${hobby}</li>`).join('')}
</ul>
</div>
`;
console.log(bio);
// Output:
// <div class="profile">
// <h2>Alex</h2>
// <p>Hobbies:</p>
// <ul>
// <li>coding</li><li>reading</li><li>hiking</li>
// </ul>
// </div>
Escaping Characters in Template Literals
To include a backtick within a template literal, you need to escape it with a backslash:
const code = `Use the \`console.log()\` method to print to the console`;
console.log(code); // Output: Use the `console.log()` method to print to the console
Similarly, to include a dollar sign followed by curly braces without triggering interpolation, escape the dollar sign:
const text = `This is not an interpolation: \${notAnExpression}`;
console.log(text); // Output: This is not an interpolation: ${notAnExpression}
Tagged Templates
Tagged templates are an advanced feature of template literals. They allow you to process template literals with a function, giving you complete control over how the template is constructed.
function highlight(strings, ...values) {
return strings.reduce((result, string, i) => {
return result + string + (values[i] ? `<strong>${values[i]}</strong>` : '');
}, '');
}
const name = 'Alice';
const age = 25;
const highlightedText = highlight`My name is ${name} and I am ${age} years old.`;
console.log(highlightedText);
// Output: My name is <strong>Alice</strong> and I am <strong>25</strong> years old.
The tagged template function receives:
- An array of string literals (the parts between expressions)
- The evaluated expressions as separate arguments
Practical Applications
Building Dynamic HTML
Template literals are perfect for creating HTML elements dynamically:
function createUserCard(user) {
return `
<div class="user-card">
<img src="${user.avatar}" alt="${user.name}">
<div class="user-info">
<h3>${user.name}</h3>
<p>${user.bio}</p>
<div class="stats">
<span>${user.followers} followers</span>
<span>${user.following} following</span>
</div>
</div>
</div>
`;
}
const userElement = createUserCard({
name: "Jane Doe",
avatar: "https://example.com/jane.jpg",
bio: "Full-stack developer passionate about UX",
followers: 1240,
following: 453
});
document.body.innerHTML = userElement;
Building Dynamic SQL Queries
Template literals can make database queries more readable:
function buildQuery(table, conditions) {
const whereClause = conditions
? `WHERE ${Object.entries(conditions).map(([key, value]) =>
`${key} = '${value}'`).join(' AND ')}`
: '';
return `
SELECT *
FROM ${table}
${whereClause};
`;
}
const query = buildQuery('users', {status: 'active', role: 'admin'});
console.log(query);
// Output:
// SELECT *
// FROM users
// WHERE status = 'active' AND role = 'admin';
Creating Email Templates
function generateEmailTemplate(user, product) {
return `
Hello ${user.firstName},
Thank you for your recent purchase of ${product.name}!
Order Details:
- Product: ${product.name}
- Price: $${product.price.toFixed(2)}
- Order ID: ${product.orderId}
Your item will be shipped to:
${user.address.street}
${user.address.city}, ${user.address.state} ${user.address.zip}
Thank you for shopping with us!
Best regards,
The Store Team
`;
}
const email = generateEmailTemplate(
{
firstName: "John",
address: {
street: "123 Main St",
city: "Anytown",
state: "CA",
zip: "12345"
}
},
{
name: "Wireless Headphones",
price: 79.99,
orderId: "ORD-12345"
}
);
Benefits of Template Literals
- Improved readability: Code is easier to read and understand compared to complex string concatenation.
- String interpolation: Direct embedding of variables and expressions within strings.
- Multi-line support: No need for escape characters or concatenation to create multi-line strings.
- Expression evaluation: Any valid JavaScript expression can be used within
${}
. - Advanced functionality: Tagged templates provide powerful string processing capabilities.
Common Pitfalls to Avoid
- Forgetting to escape special characters: Remember to escape backticks with ```.
- Security concerns: Be careful when using user input in template literals, especially when generating HTML or SQL queries, to avoid injection attacks.
- Overuse for complex HTML: For very complex UI, consider using a templating library or framework instead.
Summary
Template literals are a powerful feature in modern JavaScript that significantly improves how we work with strings. They enable cleaner, more readable code through string interpolation, multi-line support, and tagged templates.
By mastering template literals, you can write more expressive and maintainable JavaScript code, especially when dealing with complex string operations like generating HTML, building queries, or creating formatted text.
Exercises
-
Convert the following string concatenation to a template literal:
javascriptconst product = { name: "Laptop", price: 999.99 };
const message = "The " + product.name + " costs $" + product.price + "."; -
Create a template literal that generates an HTML list from an array of items.
-
Write a tagged template function that automatically escapes HTML special characters in interpolated values.
-
Create a template literal that formats a date object into a human-readable string.
-
Build a SQL query builder using template literals that prevents SQL injection.
Additional Resources
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)