Let's create a tagged template string, that is, process the template string literal using a function. Let's implement the tag function to do the same thing as the default function. Here is an example to demonstrate this:
const tag = function(strings, aPLUSb, aSTARb) { // strings is: ['a+b equals', 'and a*b equals'] // aPLUSb is: 30 // aSTARb is: 200 return 'SURPRISE!';};const a = 20;const b = 10;let str = tag `a+b equals ${a+b} and a*b equals ${a*b}`;console.log(str);
The output is as follows:
SURPRISE!
What just happened? Using a tag function, whatever you return is the final value assigned to the variable. The first argument, strings, contains all the static strings in your template literal, as an array. The elements ...