Previously I wrote an article which looked at template literals which were introduced with ES6 (if you missed it, you can find it here). It got a great reception on Medium and sparked plenty of conversation on Reddit. Although most of the discussions that took place talked about the benefits and use cases for template literals, people were also interested in the more advanced and less commonly spoken about feature, tagged template literals. I previous didn’t touch on this as it was outside the scope of the article, but as there seems to be a demand, I have written this follow up article to cover the topic.

Tagged Template Literals

Template literals are great and allow you to create strings with embedded javascript expressions in a very clean and simple to read syntax. But where they really stand out is when you start to understand and use tagged template literals. Tagged template literals basically allow you to parse the template literals using a function, which is passed the template literal and its broken down interpreted data.

Lets look at an example.

The tag function that is passed data from the template literally for which the literal will be processed. The function automatically breaks down the template literal and passes the data contained in it as seperate arguments. The first being an array of the literal strings contained in the template, followed by a list of the processed substitution expressions as they interpreted by Javascript.

In the above example, the first parameter of the tag function literals would be ['Hello ', '.'] This is an array of the actual literal strings contained in the template literal, the breakdown of this array is caused by the ${name} variable breaking the literal string. The second parameter is the Javascript interpretation of ${name} which is ‘Dave’. If the template literal included multiple substitute expressions then the tag function would receive each of these as seperate arguments.

Here is another example showing a tagged template literal with 3 substitute expressions, each being passed into the tag function separately.