What are template literals?
Template literals are a feature introduced in ECMAScript 2015 (ES6) that provide a more powerful and flexible way to work with strings in JavaScript compared to traditional string literals. They are enclosed by backticks (`) instead of single or double quotes.
What are Template Literals?
Template literals (also known as template strings) allow for string interpolation, multi-line strings, and tagged templates. They greatly improve readability and maintainability when dealing with complex string manipulations.
Multi-line Strings
One of the simplest benefits of template literals is the ability to create strings that span multiple lines without needing explicit newline characters (\n). The whitespace and line breaks within the backticks are preserved.
const multiLineString = `This is a string
that spans
multiple lines.`;
const betterMultiLineString = `This is a string
that spans
multiple lines
using template literals.`;
console.log(multiLineString);
console.log(betterMultiLineString);
Embedded Expressions (String Interpolation)
Template literals provide an easy way to embed expressions inside string literals. This is done using the syntax ${expression}. The expression inside the curly braces will be evaluated and its result will be converted to a string and inserted into the template literal.
const name = 'Alice';
const age = 30;
const greeting = `Hello, my name is ${name} and I am ${age} years old.`;
const sum = 5 + 3;
const calculation = `The sum of 5 and 3 is ${sum}. (Also ${5 + 3})`;
console.log(greeting);
console.log(calculation);
Tagged Templates
Tagged templates are a more advanced form of template literals. They allow you to parse template literals with a function. The 'tag' is a function that precedes the template literal. This function receives an array of string literals and then the values of the embedded expressions as arguments. Tagged templates can be used for things like safely escaping HTML, internationalization, or specialized string processing.
function highlight(strings, ...values) {
let str = '';
strings.forEach((string, i) => {
str += string;
if (values[i]) {
str += `<b>${values[i]}</b>`;
}
});
return str;
}
const name = 'Bob';
const occupation = 'developer';
const output = highlight`My name is ${name} and I am a ${occupation}.`;
console.log(output); // Output: My name is <b>Bob</b> and I am a <b>developer</b>.
Advantages of Template Literals
- Improved Readability: Complex string concatenations become much cleaner and easier to understand.
- Conciseness: Reduces the need for '+' operators for string concatenation and '\n' for newlines.
- Error Reduction: Minimizes common errors associated with manual string concatenation.
- Flexibility: Tagged templates provide powerful tools for custom string processing.
Browser Support
Template literals are widely supported in all modern web browsers (Chrome, Firefox, Safari, Edge, Opera) and Node.js environments. For older browsers, transpilation using tools like Babel is necessary.