logo

Tagged Template Literals

January 27, 2021

One feature that comes along with template literals and I was not aware of is Tagged Template Literals.

Tag template literals allow us to parse template strings with a function by placing the function name before the template string. It can be any function that you created.

The first argument to a tag function is an array containing the template strings, and the remaining arguments are the interpolated values. The tag function performs any operations on those arguments and returns the manipulated string.

Let's create a tagFunc function and console out the parameters to see what they will contain.

function tagFunc(strings, ...expressions) {
  console.log(strings);
  console.log(expressions);
}

By using the tagFunc as the tagged template function we can pass a string as below:

const element = "accordion";
const isOpen = true;
const sentence = tagFunc`The ${element} is ${isOpen ? "open" : "closed"}`;
console.log(sentence);

The result from console logging the strings and expressions is the following:

(3) ["The ", " is ", "", raw: Array(3)]
(2) ["accordion", "open"]

There is also a special property available on the first argument to the tag function. The raw property is only available on the strings argument and can be accessed using strings.raw. This property contains the strings without processing the escape characters from it.

To better understand this behavior, let's consider the following example:

function rawTagFunc(strings) {
  console.log(strings.raw[0]);
}

rawTagFunc`This is a \n\t easy to read \t sentence.`;

This will result in: This is a \n\t easy to read \t sentence..

When should I use a tag function you might ask?

You can use a tag function to perform whatever operations you might want on the arguments and return the manipulated string, or you return something completely different.

const name = "Dino";
const age = 1;

function myTag(strings, ...values) {
  let sentence = "";
  strings.forEach((string, idx) => {
    sentence += `${string}${values[idx] || ""}`;
  });
  return sentence;
}

let output = myTag`${name} is ${age} year${age != 1 && "s"} old.`;
console.log(output);
// "Dino is 1 year old."