DEV Community

Nhan Nguyen
Nhan Nguyen

Posted on

JavaScript Tag Function

Follow MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#tagged_templates

Tagged Templates - A more advanced form of template literals are tagged templates.

Tags allow you to parse template literals with a function. The first argument of a tag function contains an array of string values. The remaining arguments are related to the expressions.

The tag function can then perform whatever operations on these arguments you wish, and return the manipulated string. (Alternatively, it can return something completely different, as described in one of the following examples.)

The name of the function used for the tag can be whatever you want.

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 < 100 ? "youngster" : "centenarian";

  // 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}.`;

console.log(output);
// That Mike is a youngster.
Enter fullscreen mode Exit fullscreen mode

We can also check the Prisma Raw Queries feature to see how the tag function can be used.

const result = await prisma.$queryRaw`SELECT * FROM User`;
Enter fullscreen mode Exit fullscreen mode

I hope you found it helpful. Thanks for reading. šŸ™

Let's get connected! You can find me on:

Top comments (0)