Tagged template literals in JavaScript allow you to parse template literals using a function, giving you full control over how the string is constructed. The tag function receives an array of string parts and an array of evaluated expressions, enabling advanced use cases like SQL query sanitization, internationalization (i18n), styling with libraries like Styled Components, and custom DSLs (domain-specific languages).

Key Mechanics

  • The tag function is called with the template literal’s string parts as the first argument (an array of strings) and the interpolated values as subsequent arguments.

  • Use the rest operator (...values) to capture all interpolated values dynamically.

  • The first argument (strings) has one more element than the number of interpolated expressions, as it splits the template at each expression.

Example: Basic Usage

function highlight(strings, ...values) {
  let result = '';
  strings.forEach((str, i) => {
    result += str + (values[i] || '');
  });
  return result;
}

const name = 'Snickers';
const age = 100;
const sentence = highlight`My dog's name is ${name} and he is ${age} years old`;
console.log(sentence); // "My dog's name is Snickers and he is 100 years old"

Advanced Use Cases

  • SQL Injection Prevention: Tag functions can separate query structure from user input, preventing injection attacks by treating values as parameters.

  • JSX-like Syntax: Libraries like jsx can use tagged templates to render HTML-like syntax without string concatenation.

  • Styling: Frameworks like Styled Components use tagged templates to generate CSS-in-JS with dynamic styling.

  • Internationalization: Tag functions can handle pluralization, gender, and locale-specific formatting.

Note: Tag functions don’t need to return strings — they can return any value, including objects or DOM elements.

Tagged template literals take the form of (strings: string[], ...values: any[]): any.

In your example,

let a = (x) => console.log(x);
a`1234`; // prints "Array [ "1234" ]"

x has the type string[], which is an array of all non-interpolated strings (basically anything that's not inside ${}). Because there are no interpolations, the array contains one element (the string "1234"). This is what is passed as the first argument to your function a.

Only template literals can be "tagged" with a function identifier, which is why you've noticed that it doesn't work with single or double-quoted strings, only backticks. I presume it would throw a syntax error if you tried to do it with a regular string, though I haven't tested that.

If you wanted to interpolate a value, you'd do so by receiving the value in the function (which is used as the tag) by adding additional parameters. Note that it is not a single parameter that is an array, but rather separate parameters. You can, of course, create an array from them by using the spread operator (...), as indicated in the function signature above. As in the (modified) example provided by MDN,

const person = 'Mike';
const age = 28;

function tag(strings, person, age) {
  const str0 = strings[0]; // "That "
  const str1 = strings[1]; // " is a "

  // There is technically a string after
  // the final expression (in our example),
  // but it is empty (""), so disregard.
  // const str2 = strings[2];

  const age_description = age > 99 ? 'centenarian' : 'youngster';
  return [str0, name, str1, ageDescription].join('');
}

const output = tag`That ${person} is a ${age}`;

console.log(output); // "That Mike is a youngster"

Note that as indicated in the comments, there is always a leading and trailing string, even if it happens to be empty. As such, if you began a template literal with an interpolation, strings[0] would be an empty string. In the same manner, ending with an interpolation leaves a trailing empty string, though this isn't as notable (a leading interpolation shifts all indexes by one, a trailing doesn't affect them).

Answer from jhpratt on Stack Overflow
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Template_literals
Template literals (Template strings) - JavaScript | MDN
Template literals are literals delimited with backtick (`) characters, allowing for multi-line strings, string interpolation with embedded expressions, and special constructs called tagged templates.
🌐
Wes Bos
wesbos.com › tagged-template-literals
Tagged Template Literals - Wes Bos
October 25, 2016 - The way the tag template works is you simply make a function, and you take the name of the function that you want to run against the string, and you just put the name right in front of the template:
Discussions

How do tagged template literals work in JavaScript? - Stack Overflow
Also, why it doesn't work when using quotes or double quotes for declaring the string literal? ... Had never heard of this concempt before, just checked the docs, thank you kindly @jhpratt! ... Just updated my answer. Hopefully it gives a bit of an intro to tagged template literals, given there's ... More on stackoverflow.com
🌐 stackoverflow.com
[RFC] Support for tagged template literals - Development - ReScript Forum
Resurfacing from this thread. Binding to Tagged template function - #37 by zth Tagged Template RFC I’ve compiled this thread’s discussions into a single post here for renewed discussion. Github issue to come. Popular JS libraries implement tagged templates (MDN) to provide some really ergonomic ... More on forum.rescript-lang.org
🌐 forum.rescript-lang.org
1
10
August 15, 2022
Angular 20: Nuovi Tagged Template Literals nelle Espressioni ...
🌐 r/angular
How to Use Tagged Templates?
I usually use template strings to simplify creating formated strings and I use taggad template to, for example, escape the given string values (like to prevent SQL injection when building different SQL queries). More on reddit.com
🌐 r/learnjavascript
7
0
February 5, 2025
🌐
Reddit
reddit.com › r/learnjavascript › how to use tagged templates?
r/learnjavascript on Reddit: How to Use Tagged Templates?
February 5, 2025 -

I see under Template Literals that it's possible to submit a function in front of the literal. Why would you do this, rather than write a function that returns the string you need?

I've come up with two possibilities. One, it might allow you to write things to the DOM in a way similar to React. Second, I saw a YouTube video on declarative programming.

Are tagged template literals used for those purposes? Are there other reasons to use them?

TIA!

🌐
Medium
yigitatak.medium.com › tagged-template-literals-in-javascript-es6-18a2102b310d
Tagged Template Literals in JavaScript ES6 | by Yiğit Atak | Medium
March 28, 2022 - This is how you call tag functions. This is the main difference between a regular function and a tag function. We defined a tag function, we called it “tagFunction”, it takes our template literal as a parameter and simply returns a string, “awesome.” That’s a bit dull though.
Top answer
1 of 1
5

Tagged template literals take the form of (strings: string[], ...values: any[]): any.

In your example,

let a = (x) => console.log(x);
a`1234`; // prints "Array [ "1234" ]"

x has the type string[], which is an array of all non-interpolated strings (basically anything that's not inside ${}). Because there are no interpolations, the array contains one element (the string "1234"). This is what is passed as the first argument to your function a.

Only template literals can be "tagged" with a function identifier, which is why you've noticed that it doesn't work with single or double-quoted strings, only backticks. I presume it would throw a syntax error if you tried to do it with a regular string, though I haven't tested that.

If you wanted to interpolate a value, you'd do so by receiving the value in the function (which is used as the tag) by adding additional parameters. Note that it is not a single parameter that is an array, but rather separate parameters. You can, of course, create an array from them by using the spread operator (...), as indicated in the function signature above. As in the (modified) example provided by MDN,

const person = 'Mike';
const age = 28;

function tag(strings, person, age) {
  const str0 = strings[0]; // "That "
  const str1 = strings[1]; // " is a "

  // There is technically a string after
  // the final expression (in our example),
  // but it is empty (""), so disregard.
  // const str2 = strings[2];

  const age_description = age > 99 ? 'centenarian' : 'youngster';
  return [str0, name, str1, ageDescription].join('');
}

const output = tag`That ${person} is a ${age}`;

console.log(output); // "That Mike is a youngster"

Note that as indicated in the comments, there is always a leading and trailing string, even if it happens to be empty. As such, if you began a template literal with an interpolation, strings[0] would be an empty string. In the same manner, ending with an interpolation leaves a trailing empty string, though this isn't as notable (a leading interpolation shifts all indexes by one, a trailing doesn't affect them).

🌐
DEV Community
dev.to › carlosrafael22 › understanding-tagged-template-literal-in-js-49p7
Understanding Tagged Template Literal in JS - DEV Community
January 17, 2021 - They are a more advanced form of template literals which allow us to parse template literals with a function, giving us more control over how we want this string to be parsed. The Tagged in the name is because the template literal was "tagged" ...
Find elsewhere
🌐
Jim Nielsen's Blog
blog.jim-nielsen.com › 2019 › jsx-like-syntax-for-tagged-template-literals
JSX-Like Syntax for Tagged Template Literals in JavaScript - Jim Nielsen’s Blog
July 16, 2019 - Read it? Ok so with tagged template literals you can control how the string inside the back-ticks gets made. In our case, that means we can support a more JSX-like syntax in our template literals. We can detect the value of the expression that was evaluated and, depending on its type, we can output the value we would expect.
🌐
Frontend Masters
frontendmasters.com › courses › js-recent-parts › tagged-templates
Tagged Templates - JavaScript: The Recent Parts | Frontend Masters
[00:00:41] And what that's actually signifying, you are declarative tagging this string to say when it finishes i want it to before, i'm sorry before it finishes i want it to be processed with this function. So it's actually a function call it didn't really look like it but it's a special kind of function call, called a tagged template string, okay, or tagged template literal.
🌐
freeCodeCamp
freecodecamp.org › news › a-quick-introduction-to-tagged-template-literals-2a07fd54bc1d
A quick introduction to Tagged Template Literals
March 15, 2019 - Tagged template literals were enabled by a new technology introduced in ES6, called “template literals”. This is simply a syntax that makes string interpolation possible in JavaScript.
🌐
TypeScript
typescriptlang.org › docs › handbook › 2 › template-literal-types.html
TypeScript: Documentation - Template Literal Types
Similarly, the callback for a change to age should receive a number argument. We’re naively using any to type the callback’s argument. Again, template literal types make it possible to ensure an attribute’s data type will be the same type as that attribute’s callback’s first argument.
🌐
Dmitriid
dmitriid.com › tagged-template-literals-are-the-worst-addition-to-javascript
Tagged Template Literals Are the Worst Addition to Javascript · A Place Where Even Mammoths Fly
March 5, 2019 - Putting a template literal after an expression triggers a function call, similar to how a parameter list (comma-separated values in parentheses) triggers a function call. The previous code is equivalent to the following function call (in reality, first parameter is more than just an Array, but that is explained later). tagFunction(['Hello ', ' ', '!'], firstName, lastName)
🌐
Jinja
jinja.palletsprojects.com › en › stable › templates
Template Designer Documentation — Jinja Documentation (3.1.x)
You must not add whitespace between the tag and the minus sign. ... It is sometimes desirable – even necessary – to have Jinja ignore parts it would otherwise handle as variables or blocks. For example, if, with the default syntax, you want to use {{ as a raw string in a template and not start a variable, you have to use a trick. The easiest way to output a literal variable delimiter ({{) is by using a variable expression:
🌐
Exploring JS
exploringjs.com › js › book › ch_template-literals.html
Using template literals and tagged templates ES6
Template literals always produce strings. The expression in line A is a tagged template.
🌐
Konstantin
konstantin.digital › blog › tagged-template-literals-how-tools-like-styled-components-work
Tagged Template Literals - How Tools Like Styled Components Work
November 10, 2022 - Have you ever wondered how syntactical sugar like `styled` just magically works? Let’s recreate this functionality using tagged template strings in Javascript.
🌐
mike.williamson
mikewilliamson.wordpress.com › 2018 › 10 › 22 › tagged-template-literals-and-the-hack-that-will-never-go-away
Tagged template literals and the hack that will never go away – mike.williamson
November 25, 2025 - Tagged template literals were added to the JavaScript as part of the 2015 update to the ECMAScript standard. While a fair bit has been written about them, I’m going to argue their significanc…
🌐
ReScript Forum
forum.rescript-lang.org › development
[RFC] Support for tagged template literals - Development - ReScript Forum
August 15, 2022 - Resurfacing from this thread. Binding to Tagged template function - #37 by zth Tagged Template RFC I’ve compiled this thread’s discussions into a single post here for renewed discussion. Github issue to come. Popular JS libraries implement tagged templates (MDN) to provide some really ergonomic ...
🌐
DigitalOcean
digitalocean.com › community › tutorials › js-tagged-template-literals
Tagged Template Literals in JavaScript (ES6 / ES2015) | DigitalOcean
February 7, 2017 - Tagged template literals allow you to pass a function to be executed on the literal before it gets evaluated.
🌐
Tektutorialshub
tektutorialshub.com › home › typescript › typescript tagged templates
Typescript Tagged Templates - Tektutorialshub
March 15, 2023 - The Typescript Tagged Templates allow us to tag template strings or template literals using a function (Tagged function). Once tagged, the Templates strings allow us to parse the template literals using the Tagged function.