DEV Community

Cover image for Tagged Template Literals in a Nutshell
shadowtime2000
shadowtime2000

Posted on • Originally published at h.shadowtime2000.com on

Tagged Template Literals in a Nutshell

Hi, in this post I will be writing about tagged template literals. Tagged template literals are like normal template literals but with more control given to functions you pass these as parameters to.

Syntax

The syntax for tagged template literals is pretty simple. It uses backticks like normal template literals and allows you to have JavaScript expressions inside ${} parts. Tagged template literals can only be used on functions though and when you are using them you omit the parentheses on the function call.

taggedTemplateLiteralFunc`
    the stuff i put ${here}
`
Enter fullscreen mode Exit fullscreen mode

What They Do

So basically, instead of just calling the function as if it was a simple template literal being put as the first argument, it will take the string and compose it into a couple arguments which are called. It will follow the loop of taking all the string until it finds an interpolated expression, add that to one array, then take the value of that expression, and add that to another array. The JS engine will follow that loop until it reaches the end of the template literal. The first argument to the function is the first array, and then the second array is spread as if the ... spread operator was used on it as all of the rest of the arguments of the function.

This is an example of the same function being called with the same parameters just without the tagged template literals:

myFunction`
1 + 2 = ${1 + 2}3 + 51 = ${3 + 51} = ${3 + 51}
`

myFunction(["1 + 2 = ", "3 + 51 = ", " = "], 3, 54, 54);
Enter fullscreen mode Exit fullscreen mode

📚 Reading more:
MDN

Other Articles You Might Like

  1. What is ES6 Tree Shaking
  2. Everything You Don't Know About ES Modules

Top comments (0)