TIL: Template Literals with Tag Functions in JavaScript

Last updated: Mon Mar 11 2024

If you’ve used JavaScript for more than about a week, you’re probably familiar with template literals, as used for string interpolation:

const now = Date.now();
console.log(`It is currently ${now}.`)

It turns out this is actually part of a broader API in JavaScript. You can provide a “tag function”, specified at the start of the interpolated string, which operates on the components of the templated string and its injected values. A tag function can return any value, not just a string! From the MDN docs:

const output = myTag`That ${person} is a ${age}.`;
// Basically, this is the same as calling myTag(["That ", " is a ", "."], person, age)

One place this is used “in the wild” is the Lit framework, which provides an html tag function for reactive templating:

const name = 'world';
const sayHi = html`<h1>Hello ${name}</h1>`;
render(sayHi, document.body);

References