Template Literals (also called Template Strings) were introduced in ES6. They are literals delimited with backticks (`` ` ``) instead of standard quotes and provide several powerful features for working with text.
To use template literals, you wrap your string in backticks. You can use both single and double quotes inside a template literal without needing escape characters.
let text = `He said "It's a beautiful day"`;
console.log(text); // He said "It's a beautiful day"
One of the biggest advantages of template literals is the ability to write strings across
multiple lines without needing special characters like \n.
let poem = `
The woods are lovely, dark and deep,
But I have promises to keep,
And miles to go before I sleep.
`;
Template literals allow you to embed variables and expressions directly into your string
using the ${...} syntax. This is much cleaner than traditional concatenation
with +.
let firstName = "Mim";
let lastName = "Akter";
let fullName = "Welcome " + firstName + " " + lastName + "!";
let firstName = "Mim";
let lastName = "Akter";
let fullName = `Welcome ${firstName} ${lastName}!`;
You can also perform mathematical or logical calculations inside the ${...}
placeholders.
let price = 100;
let tax = 0.15;
let total = `Total price: ${price * (1 + tax)}`;
// Result: Total price: 115
Template literals are perfect for generating HTML dynamically in JavaScript:
let header = "Templates Intro";
let tags = ["template literals", "javascript", "es6"];
let html = `<h2>${header}</h2><ul>`;
for (const x of tags) {
html += `<li>${x}</li>`;
}
html += `</ul>`;
${variable} to embed values${}