DEV Community

kohki_takatama
kohki_takatama

Posted on

1

TIL: Tag Function / Tagged Template Literals

Overview 🔍

Tagged Functions, also known as Tagged Template Literals, are an advanced feature of template literals introduced in ES6 (2015). They enable more control over how template literals are processed, allowing for custom formatting, parsing, or even validation.

One popular use case for tagged template literals is in GraphQL for building query strings dynamically.


Syntax

Definition

A tagged template literal is a combination of a "tag function" and a template literal. The tag function receives the literal's strings and interpolated values as arguments, enabling custom processing.

Here’s a basic example:

const bar = "var bar";

function tag(strings, ...values) {
  console.log(strings); // Array of string literals
  console.log(values);  // Array of interpolated values
}
Enter fullscreen mode Exit fullscreen mode

Usage

tag`foo ${bar} baz`;

// Output:
// ['foo ', ' baz']  // Array of strings
// ['var bar']       // Array of values
Enter fullscreen mode Exit fullscreen mode

Use Cases

1. Internationalization (i18n)

Tagged template literals can be used to process strings dynamically for localization.

Example:

function i18n(strings, ...values) {
  const translations = {
    "Hello, ": "Hola, "
  };

  return strings.reduce((acc, str, i) => {
    const translatedStr = translations[str] || str; // Translate if possible
    return acc + translatedStr + (values[i] || '');
  }, '');
}

const name = "Alice";
const result = i18n`Hello, ${name}!`;
console.log(result);
// Output: "Hola, Alice!"
Enter fullscreen mode Exit fullscreen mode

2. GraphQL

In GraphQL, tagged template literals are widely used to define and manipulate query strings.

Example:

const query = gql`
  query {
    user(id: 1) {
      name
      age
    }
  }
`;
Enter fullscreen mode Exit fullscreen mode

3. Handling Arguments with Tagged Template Literals

Tagged template literals can also process arguments by passing an additional value to the tag function and applying functions within the template literal.

Example:

function tagged(baseValue) {
  return function(strings, ...functions) {
    return strings.reduce((acc, str, i) => {
      const value = typeof functions[i] === 'function' ? functions[i](baseValue) : '';
      return acc + str + value;
    }, '');
  };
}

const result = tagged(2)`foo${n => n * 0}bar${n => n * 1}baz${n => n * 2}`;
console.log(result);
// Output:
// "foo0bar2baz4"

Enter fullscreen mode Exit fullscreen mode

Discussion and Insights 💭

Tagged template literals enable dynamic string processing with custom logic, making them ideal for use cases like query building, internationalization, and input sanitization. They improve code readability and maintainability, especially in scenarios requiring advanced string manipulation.


References

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more