Template literals use **backticks** (`` ` ``) and support: **interpolation** `${expression}` (any JS expression), **multi-line strings** (without `\n`), and **tagged templates** (a function called with the template's parts). They replace string concatenation with `+`.
1Understanding Template Literals
Template literals use backticks (` `) and support: **interpolation** ${expression} (any JS expression), **multi-line strings** (without \n), and **tagged templates** (a function called with the template's parts). They replace string concatenation with +`.
You can put any expression inside ${}: ${user.age >= 18 ? 'adult' : 'minor'} or ${arr.map(x => x * 2).join(', ')}.
const user = { name: 'Alice', age: 30 };
// Interpolation
console.log(`Name: ${user.name}, Age: ${user.age}`);
// Expression inside interpolation
console.log(`Status: ${user.age >= 18 ? 'adult' : 'minor'}`);
// Multi-line
const html = `
<div class="card">
<h2>${user.name}</h2>
</div>
`;2Practical Example
Here is a real-world application of Template Literals showing how it is used in production JavaScript code.
// Tagged template literal
function highlight(strings, ...values) {
return strings.reduce((result, str, i) => {
const val = values[i - 1];
return result + `<mark>${val}</mark>` + str;
});
}
const price = 42;
const msg = highlight`The price is ${price} dollars`;
console.log(msg); // The price is <mark>42</mark> dollars3Best Practices
Follow these guidelines when working with Template Literals:
1. Use template literals instead of string concatenation
2. Use for multi-line HTML templates
3. Use tagged templates for SQL query sanitization, i18n, styled-components
Tip: You can put any expression inside ${}: ${user.age >= 18 ? 'adult' : 'minor'} or ${arr.map(x => x * 2).join(', ')}.
const user = { name: 'Alice', age: 30 };
// Interpolation
console.log(`Name: ${user.name}, Age: ${user.age}`);
// Expression inside interpolation
console.log(`Status: ${user.age >= 18 ? 'adult' : 'minor'}`);
// Multi-line
const html = `
<div class="card">
<h2>${user.name}</h2>
</div>
`;