title: Tagged Template Literals in a Nutshell published: true date: 2021-01-27 02:14:51 UTC tags: JavaScript canonical_url: https://h.shadowtime2000.com/tagged-template-literals-in-a-nutshell cover_image: https://carbon.now.sh/?bg=rgba%28171%2C+184%2C+195%2C+1%29&t=solarized+dark&wt=none&l=javascript&ds=true&dsyoff=20px&dsblur=68px&wc=true&wa=true&pv=56px&ph=56px&ln=false&fl=1&fm=Hack&fs=14px&lh=133%25&si=false&es=2x&wm=false&code=taggedTemplateLiteralFunction%2560%250A%2509my%2520%2524%257Btagged%257D%2520template%2520%2524%257Bliteral%2520%252B%2520%2522function%2522%257D%250A%2560%253B
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}
`
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);
📚 Reading more: MDN
Other Articles You Might Like
Back | DEV.toshadowtime2000
If you are looking at this you probably wonder who I am; teenage open source maintainer