DEV Community

Abhirup Datta
Abhirup Datta

Posted on

4 3

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.


Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay