What is tagged template literal in JavaScript
Everything you need to know about tagged functions.
Before ES6 if we have to concatenate two strings then we have do something like this:
ES6 introduces new concept called Template Literals
or some times called String Interpolation
. Template Literals
are used to concatenate strings with the use back-ticks and ${variableName}
.
If we have to concatenate strings using TemplateLiteral
then we have to wrap our string inside two back-ticks. And inside that we can use any JS variable of expression as well.
What is Tagged Template Literal or Tagged Functions
Template Literal
introduces this new concept of Tagged Template Literal
or sometimes called Tagged Function
.
Tagged Function
take leverage of Template Literal
and provide us a way to call function on Template Literal
Directly.
We call a function on template literal by simply writing the function name before the starting of Template Literal
.
When we call any function in such way, then the called function here functionName
, receives fixed set of arguments.
- First argument is always an array of strings, without JS variables.
- After first argument we receive comma separated arguments, which includes used JS variables, functions or expressions.
Let us understand this by an example
Flavour 1: When there is no variable
, expression
or function call
is present in template literal.
Flavour 2: When there are variables
, expressions
or function calls
in present in template literal.
Thing to note here, we are getting undefined
added in the last.
This is because a template literal always has more Strings than Values.
What does this mean?
Let’s first understand this and then we will solve above issue.
Whenever we use tagged template literal, we know that first argument is an array containing strings which aren’t using any JS variable, and then comma separated JS values.
Interesting thing about strings
array which is the first argument is that, it also include word boundaries.
This clearly shows, template literal always has more Strings than Values.
To Solve our above problem, simple check if the value is there, other wise return empty string.
Use Cases:
1. We can use this to transform our strings, like adding special symbols or sometimes HTML tags.
2. This is mostly used in Styled Components.
Thanks for reading, I hope this made you to learn something new about template literals.