Template literals are essentially string literals that allow for embedded expressions, making it easier to create multi-line strings and concatenate strings. This is a new feature of ES6 that simplifies certain coding tasks.
+
operator to concatenate multiple strings. While it works, it can become tedious and error-prone, especially when dealing with large strings.${}
syntax to include expressions.+
operator and quotes to concatenate multiple strings. Instead, we can use placeholders and expressions to create a cleaner, more readable code.\n
escape character to denote a new line, we can simply create a new line in the template literal. This makes it easier to structure our code and create readable strings.Let's take a look at some code examples to illustrate these concepts.
// Pre-ES6 string concatenation
const firstName = "John";
const lastName = "Doe";
const age = 30;
const greeting = "Hello, " + firstName + " " + lastName + "! You are " + age + " years old.";
console.log(greeting); // Hello, John Doe! You are 30 years old.
// Using backticks to create a template literal
const greetingTemplate = `Hello, ${firstName} ${lastName}! You are ${age} years old.`;
console.log(greetingTemplate); // Hello, John Doe! You are 30 years old.
// Creating a multiline string using a template literal
const list = `
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
`;
// Outputting the multiline string to the DOM
const myDiv = document.getElementById("myDiv");
myDiv.innerHTML = list;
As you can see, using template literals makes our code more readable and easier to write. We can create multi-line strings and use placeholders for expressions, which makes it easier to structure our code and make it more human-readable.
It is possible to use template literals inside other template literals. This can be useful when you want to generate dynamic content, such as a list of items. Here is an example:
const pizzaToppings = ["cheese", "mushrooms", "sauce", "pepperoni", "pineapple"];
const pizzaHTML = `
<article>
<h1>Pizza ingredients</h1>
<ul>
${pizzaToppings.map(topping => `<li>${topping}</li>`).join("\n")}
</ul>
</article>
`;
console.log(pizzaHTML);
Output:
<article>
<h1>Pizza ingredients</h1>
<ul>
<li>cheese</li>
<li>mushrooms</li>
<li>sauce</li>
<li>pepperoni</li>
<li>pineapple</li>
</ul>
</article>
map
function to generate an array of list items (<li>
) for each pizza topping, and then use the join
function to join the array elements into a string with newlines.Tag template literals are a more advanced feature of template literals that allow you to use a function to process the template literal. This can be useful for things like localization or sanitizing user input. Here is an example:
function upper(strings, ...values) {
let result = "";
for (let i = 0; i < strings.length; i++) {
result += strings[i];
if (i < values.length) {
result += values[i].toUpperCase();
}
}
return result;
}
const name = "Chris";
const age = 27;
console.log(upper`I am ${name}. I am ${age} years old.`);
Output: I am CHRIS. I am 27 YEARS OLD.
In the example, we define a functionupper
that takes an array of strings and an array of values, and returns a string with the values converted to uppercase.