3 min read
•Question 25 of 50easyWhat are Template Literals in JavaScript?
Understanding template strings and tagged templates.
What You'll Learn
- Template literal syntax
- Multi-line strings
- Tagged templates
Basic Syntax
code.jsJavaScript
const name = 'John';
const age = 30;
// String concatenation (old)
const msg1 = 'Hello, ' + name + '! You are ' + age + '.';
// Template literal
const msg2 = `Hello, ${name}! You are ${age}.`;
// Expressions
const msg3 = `Next year you'll be ${age + 1}.`;Multi-line Strings
code.jsJavaScript
// Old way
const html1 = '<div>\n' +
' <p>Content</p>\n' +
'</div>';
// Template literal
const html2 = `
<div>
<p>Content</p>
</div>
`;Tagged Templates
code.jsJavaScript
function highlight(strings, ...values) {
return strings.reduce((acc, str, i) => {
return acc + str + (values[i] ? `<mark>${values[i]}</mark>` : '');
}, '');
}
const name = 'John';
const result = highlight`Hello, ${name}!`;
// 'Hello, <mark>John</mark>!'Nested Templates
code.jsJavaScript
const items = ['Apple', 'Banana', 'Orange'];
const html = `
<ul>
${items.map(item => `<li>${item}</li>`).join('')}
</ul>
`;