This page looks best with JavaScript enabled

Tagged Templates in Javascript

 ·   ·  ☕ 2 min read

Tagged templates allow our beloved template literals to be taken to a whole new level.

The typical use of a template literal is below -

1
2
3
4
5
let x = 1;
let y = 5;

console.log(`x is ${x}, y is ${y}`);
// x is 1, y is 5

Template literals allow us to avoid stupid statements like this -

1
2
console.log("x is " + x + ", y is " + y);
// x is 1, y is 5

Template literals are cool.

Tagged templates take the above function in a different way -

1
2
3
4
5
6
7
8
9
let x = 1;
let y = 5;

sum`x is ${x} y is ${y}`;

function sum(str, ...values) {
  console.log(str, values);
  // [ 'x is ', 'y is ', '' ] [ 1, 5 ]
}

The above code ‘tags’ a template literal x is ${x} y is ${y} with sum.

Sum is also typically a function, which will have two arguments -

  1. plain text in the template literal
  2. values supplied in the template literal

Tagged templates are just plain functions masquerading for specific use cases.
The above tagged template can be represented as -

1
2
3
4
// code, code and code
function sum([str1, str2], [value1, value2]) {
  // more code
}

I have not used tagged templates that much, but they should be super useful when -

  • reformatting strings/ user input
  • trying to dissemble & reassemble part or whole of template literals (e.g see es2015-i18n-tag - translate literal strings and seamlessly use them with specified values)
  • styling components (see styled components! )

Further Reading

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things