Sub topic 1
A Quick Refresher on Template Literals
Tagged templates are built on ordinary template literals, so this chapter reviews how those work first. Everything here applies to untagged literals. Later chapters show what changes when a function name is placed in front.
Prerequisites
This tutorial assumes you already know:
- JavaScript functions and rest parameters (
...args) - Arrays and
Array.prototype.reduce - String escape sequences such as
\nand\t - That template literals use backticks, even if you rarely use them beyond simple interpolation
Backticks and Substitutions
A template literal is a string literal written between backticks (` `) instead of single or double quotes. Inside it, ${expression}` marks a substitution. JavaScript evaluates the expression, converts the result to a string, and inserts it at that position.
const item = 'coffee';
const price = 3.5;
const qty = 2;
const line = `${qty} x ${item} = $${(price * qty).toFixed(2)}`;
console.log(line); // 2 x coffee = $7.00Any expression can go inside ${}: arithmetic, function calls, ternaries, even another template literal. A $ that isn't followed by { is just a character, which is why $${...} above prints a dollar sign and then the value.
How Values Become Text
An untagged template literal converts each substitution to a string, much like String(value) does. This is easy to forget when the value is an object or an array:
const user = { name: 'Ada' };
const tags = ['js', 'web'];
console.log(`User: ${user}`); // User: [object Object]
console.log(`Tags: ${tags}`); // Tags: js,web
console.log(`Missing: ${undefined}`); // Missing: undefinedThe conversion always happens, and you cannot change it. Later chapters show that a tag function receives the original values before any conversion, which is one of the main reasons to write a tag.
Multiline Strings
A template literal can span lines. The line breaks and all leading whitespace become part of the string.
const message = `Dear Ada,
Your order has shipped.
Thanks!`;
console.log(message.split('\n'));
// [ 'Dear Ada,', ' Your order has shipped.', 'Thanks!' ]Escapes Still Work
Escape sequences such as \n, \t, and \u00e9 work in template literals the same way they do in quoted strings. To write a literal backtick or a literal ${, escape it with a backslash:
console.log(`Use \`code\` here`); // Use `code` here
console.log(`Not a sub: \${x}`); // Not a sub: ${x}
console.log(`caf\u00e9`); // caféIn an untagged literal, an invalid escape such as \u followed by non-hex characters is a syntax error. Tagged templates relax this rule, which a later chapter covers.
The Structure Underneath
A template literal alternates between fixed text and substitutions. It always begins and ends with a text part, and either part can be empty. Keep this shape in mind, because a tag function receives exactly these pieces.
With two substitutions there are three text parts. That count, one more text part than substitutions, holds for every template literal.
Exercise
What does this code log, and how many static text parts does the literal contain? const a = [1, 2]; console.log(${a}${''}!);
Show answer
It logs "1,2!". The array is converted with String(), giving "1,2", and the empty string adds nothing. The literal has two substitutions, so it has three static text parts: '', '', and '!'.
Exercise
Why does Total: $${5} print "Total: $5" instead of causing an error?
Show answer
The first $ is not followed by {, so it is ordinary text. The next two characters, ${, start a substitution that evaluates 5.