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

Please leave your appreciation by commenting on this post!

Sure thing!

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay