Exploring Tagged Template Literals

In ES2015, we gained the ability to interpolate string literals.

const name = 'marques';
console.log(`My name is ${name}`);

This means we can use expressions within our strings, and they will be interpolated as long as we use the back tick (``) syntax. This alone is a great feature, but it’s not all that was added involving template literals. We also have the ability parse template literals with a function. This type of function is called a tag. It looks like this:

The first argument in your tag function foo will be an array of all of the strings. There are two strings in the above example: “My name is ” and the period “.”. The rest of the arguments are the results of the already-evaluated interpolated expressions. We use the ‘…’ rest operator to gather those results into an array. Our example above only has 1 expression, ${name}, so the “…values” array only has one element in it, [“marques”].

Here’s a slightly more robust example:

This example doesn’t really do anything special. All it is doing is parsing a template literal in the same way as when you don’t use a tag. The point here is to show what we can do in our tag function. One thing that might throw you off at first, is this part:

(idx > 0 ? values[idx - 1]: '')

That is only there because we are using a .reduce, and that means the first part of our string will be the initial value we set in the accumulator.

So what can we use this for?

We can do a lot of interesting things with this?

Here’s an example of me doing a spanish-translation lookup:

I think the best examples of using tagged template literals I’ve seen are from Max Stoiber and Glen Maddern’s styled-components, and the Apollo GraphQL’s project graphql-tag. Going off of the idea of styled-components, which has tags that will return a React component with your specified styles applied, you can create your own custom components in the same way. You can write a tag that returns an encrypted string. You can write a tag that includes HTML with variables that get parsed by your function (like in Angular). I’m very excited to see what the JS community comes up with!

In conclusion

Take some time and play around with tagged template literals. We’ve seen some pretty large and popular projects use them already, and as more people get accustomed to them, we’ll see even more.

Thanks for reading :)

Show your support

Clapping shows how much you appreciated Marques Woodson’s story.