Template literals are a modern JavaScript feature that revolutionizes string creation and manipulation. Introduced in ES6 (ECMAScript 2015), they offer a more flexible and readable way to work with strings.
Template literals are string literals that allow embedded expressions and multi-line strings. They're enclosed by backticks (`) instead of single or double quotes.
Here's how to create a simple template literal:
const name = 'World';
const greeting = `Hello, ${name}!`;
console.log(greeting); // Output: Hello, World!
Template literals make it easy to create multi-line strings without using escape characters:
const multiLine = `This is a
multi-line
string.`;
console.log(multiLine);
You can include any valid JavaScript expression within ${}
in a template literal:
const a = 5;
const b = 10;
console.log(`The sum of ${a} and ${b} is ${a + b}.`);
// Output: The sum of 5 and 10 is 15.
Template literals can be "tagged" with a function, allowing you to parse the template literal with custom logic:
function myTag(strings, ...values) {
return strings.reduce((result, str, i) =>
`${result}${str}${values[i] ? `(${values[i]})` : ''}`, '');
}
const name = 'Alice';
const age = 28;
console.log(myTag`Hello, ${name}! You are ${age} years old.`);
// Output: Hello, (Alice)! You are (28) years old.
Template literals are supported in all modern browsers. However, for older browsers, you may need to use a transpiler like Babel. Check the JavaScript Browser Compatibility guide for more details.
To deepen your understanding of modern JavaScript features, explore these related topics:
Template literals are a powerful tool in your JavaScript toolkit. They simplify string manipulation and enhance code readability. By mastering this feature, you'll write cleaner, more expressive code.