Skip to main content

Command Palette

Search for a command to run...

JavaScript Tag Function

Updated
2 min read
N

I'm Nhan. I'm a web developer from Vietnam. I have over 5 years of experience in the Angular framework.

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.*

Thetag functioncan 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.

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`;

I hope you found it helpful. Thanks for reading. 🙏

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

More from this blog

Nhan Nguyen's blog

88 posts

I’m a web developer, and I am really passionate about learning web development.