Tagged Template Literals

Tagged template literals are a relatively new feature for Javascript allowing complex string building, similar to f-strings in Python.

Here is an example from MDN[1]:

const person = "Mike";
const age = 28;

function myTag(strings, personExp, ageExp) {
  const str0 = strings[0]; // "That "
  const str1 = strings[1]; // " is a "
  const str2 = strings[2]; // "."

  const ageStr = ageExp > 99 ? "centenarian" : "youngster";

  // We can even return a string built using a template literal
  return `${str0}${personExp}${str1}${ageStr}${str2}`;

const output = myTag`That ${person} is a ${age}.`;

// That Mike is a youngster.

This is essentially the same thing as writing the argument to myTag without calling myTag at all, but what makes it so special is that you can perform arbitrary processes on these strings. This comes in handy in readability of templating functions, like zserge's experimental React clone, o[2], or other general string manipulation.


  1. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#tagged_templates
  2. Zserge's O uses them to great effect to make 'the worst React ever'

Last modified: 202301050148