Forem

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

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay