Sub topic 1
A Quick Refresher on Template Literals
Prerequisites
This chapter assumes you know JavaScript functions and rest parameters, Array.prototype.reduce, common escape sequences such as \n, and the basic backtick syntax of template literals.
Template Literals in Brief
A template literal is a string written between backticks. It can span several lines. It can also embed expressions with ${}, and each expression is evaluated and converted to a string.
const name = 'Ada';
const greeting = `Hello ${name},
welcome back.`;
console.log(greeting); // two lines: "Hello Ada," then "welcome back."What a Tag Does: Turning a Literal into a Function Call
If you put a function name directly before a template literal, it becomes a tagged template. JavaScript does not build a string in that case. It calls the function instead, which is known as the tag. You write no parentheses. The tag gets the literal's pieces as arguments and returns whatever it chooses.
Inside the Call: The Strings Array and the Values
The first argument is an array of the static text parts. Each substitution's value arrives as a separate argument after it, so you usually collect the values with a rest parameter. The strings array always has one more element than there are values. When a substitution sits at the start or end of the literal, the matching string part is empty.
function inspect(strings, ...values) {
console.log(strings); // [ 'Hello ', ', you are ', ' years old.' ]
console.log(values); // [ 'Ada', 36 ]
return strings.length - values.length; // always 1
}
const name = 'Ada';
const age = 36;
console.log(inspect`Hello ${name}, you are ${age} years old.`); // 1Rebuilding the Output by Interleaving Parts
Most tags rebuild a string by alternating string parts and values. If you call reduce without an initial value, it starts from strings[0]. The index i then begins at 1, so values[i - 1] is the value that belongs before strings[i].
function upper(strings, ...values) {
return strings.reduce(
(out, str, i) => out + String(values[i - 1]).toUpperCase() + str
);
}
const who = 'world';
console.log(upper`hello ${who}!`); // 'hello WORLD!'Exercise
For tag${a} and ${b}, what are the strings array and the values passed to tag?
Show answer
The strings array is ['', ' and ', ''] and the values are a and b. There are three string parts for two values, and the parts at the start and end are empty.