Template literals are the form of string that uses backticks, and they let you drop variables straight into the text. Once you have used them you will not want to go back to joining strings with plus signs. There are two real traps though, which are interpolating user input into HTML and nesting backticks inside each other. The previous lesson in this module covered the string methods that you will use every day, and you will see them again here, because a template literal hands you an ordinary string and every method still works on it. The next lesson in the module takes the text that you build here and splits it into pieces again.
What is a template literal?
A template literal is written with backticks instead of quotes. Inside ${...} you put an expression, and JavaScript works out its value and drops the result into the surrounding text.
const name = 'Ada';
const score = 92;
console.log(`Hello ${name}, you scored ${score}%.`);
// Hello Ada, you scored 92%.
console.log(`Total: ${10 + 5} items`);
// Total: 15 items
The braces are not decoration, because they hold a complete expression. Arithmetic, conditionals, and method calls all work inside them. Comparing that with the older way is instructive. The line 'Hello ' + name + ', you scored ' + score + '%.' produces exactly the same string, but it needs four pieces and three plus signs, and every extra piece is another place where you can forget a space or a full stop.
How do I build multi-line text?
Because the text is not delimited by quotes, a template literal can run over several lines with no escape sequences at all. That makes it the natural choice for building a block of text such as an email, a report, or a log entry.
const user = { name: 'Ada', tags: ['js', 'web'] };
const card = `${user.name}
tags: ${user.tags.join(', ')}
active: ${user.tags.length > 0}`;
console.log(card);
// Ada
// tags: js, web
// active: true
Every line break and every leading space inside the template literal becomes part of the resulting string, so line the content up carefully. A common trick is to start the content on the line after the opening backtick and then trim the result, but in ordinary code the shorter version is much easier to read.
How do I keep user text safe inside HTML?
Interpolating a value into HTML is where template literals become dangerous. The value is inserted exactly as it is, so a name that contains a quote or a tag becomes part of the markup.
function escapeHtml(value) {
const replacements = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
};
return String(value).replace(/[&<>"']/g, function (character) {
return replacements[character];
});
}
console.log(escapeHtml('<script>alert(1)</script>'));
// <script>alert(1)</script>
Two separate protections matter here, and neither one replaces the other. Escaping protects the markup, because the angle brackets become entities and the browser renders the text instead of running it. Setting text content rather than inner HTML protects the value, because when you assign to textContent the browser treats the string as text no matter what is inside it, and then no escaping function is needed at all. Use escaping when you are deliberately building an HTML string, and use textContent when you are updating an element. The second option is simpler and impossible to get wrong.
What is a tagged template?
A tagged template is a template literal with a function in front of it. That function receives the literal text chunks and the interpolated values separately, which means it gets to decide how those values are formatted, escaped, or checked.
function money(strings, values) {
let result = '';
for (let index = 0; index < strings.length; index++) {
result = result + strings[index];
if (index < values.length) {
result = result + '$' + values[index].toFixed(2);
}
}
return result;
}
console.log(money`Total: ${12.5} (tax ${1.5})`);
// Total: $12.50 (tax $1.50)
The tag receives an array of the text between the interpolations, which here is 'Total: ', ' (tax ' and ')', plus the values themselves. Because the values arrive raw instead of already being turned into text, the tag can format them as currency, escape them for HTML, or refuse them. Tagged templates are how libraries build safe query strings, sanitised markup, and internationalised text, and how component libraries turn a template into a description of what should be rendered.
What are the template literal pitfalls?
Three things trip people up, and none of them are about the syntax itself.
const name = 'Ada';
const id = 7;
console.log(`User ${id}: ${name.toUpperCase()}`);
// User 7: ADA
console.log(`\${notAVariable}`);
// ${notAVariable}
First, a backslash before the dollar sign escapes the interpolation, which is how you print a literal ${...} when the text comes from a template of your own. Second, nesting one template literal inside another one means nesting backticks, which is legal but close to unreadable, so pull the inner value out into a variable instead. Third, a template that ends with a backslash escapes the closing backtick, because a backslash starts an escape sequence inside backticks just as it does inside quotes. A stray backslash at the end of a long template produces a syntax error that points at the wrong line.
When should I reach for a template literal?
| Situation | What to use |
|---|---|
| A message with values in it | Template literal |
| Text that spans several lines | Template literal |
| Joining several string pieces | Template literal |
| A fixed string with no values | Single or double quotes |
| Building HTML markup | Template literal plus escaping, or the DOM APIs instead |
| Formatting numbers and dates | A format call inside the braces, such as toFixed or Intl |
The last row is worth expanding. A template literal does not format anything for you. ${total} inserts the raw value, so 12.5 stays 12.5 and 1234.5 stays 1234.5 instead of becoming 1,234.50. When the formatting matters, call a formatter inside the braces. Use total.toFixed(2) for a simple case, or new Intl.NumberFormat('en-IN', { style: 'currency', currency: 'INR' }).format(total) when you want proper currency formatting.
Try it yourself: write a file called receipt.js with const order = { id: 'A-1', items: [{ name: 'pen', price: 3 }, { name: 'book', price: 12 }] };. Use a template literal to print a one-line summary such as 'Order A-1 has 2 items'. Then build a multi-line receipt that shows the id, one line for each item, and the total formatted with toFixed(2). Next, write your own tag called upper that uppercases the values it receives, and print the order id through it. Finally, print a string that contains a literal dollar-brace sequence using an escaped dollar sign, and check that it appears exactly as you typed it.