DEV Community

Abhirup Datta
Abhirup Datta

Posted on

Tagged functions / Tagged templates

According to MDN docs
Tags allow you to parse template literals with a function. The first argument of a tag function contains an array of string values. The remaining arguments are related to the expressions.
Let's explore more here.

const age = 20;
function name(...args){
name`My Name is ${age}`
Enter fullscreen mode Exit fullscreen mode

This outputs

Tagged templates
So, we see the arguments of the tagged template name is an array which contains the string literals as an array as first element and the remaining arguments are related to the expression.

This abilty of processing, enables powerful features like the
Styled component syntax.

Let us see an example.
Suppose we have template string which has some expressions bounded in one div and we want to separate out each expression in their own divs.

For this we can write a tagged template which return the processed string and then we can use document.body to put it on DOM.

Here is the code

One pitfall to remember

Because tagged template can parse unicode representation, a invalid unicode will print undefined.

function name(stringExps){

Enter fullscreen mode Exit fullscreen mode

The first two function call will print © but the last one will print undefined.

Latest comments (0)