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){
  console.log(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
https://jsfiddle.net/abkhfmtz/21/


One pitfall to remember

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

function name(stringExps){
   console.log(stringExps);
}

name`\u00A9`
name`\xA9`
name`\unicode`
Enter fullscreen mode Exit fullscreen mode

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


Oldest comments (0)