DEV Community

Cover image for TIL: Template Strings used with a function
James Won
James Won

Posted on

TIL: Template Strings used with a function

ES6 introduced the handy Template literals that you probably use day-to-day to avoid string concatenation.

But what you may not know is that you can parse these template literals with a function.

This feature is called Tagged templates.

The concept is simple. You can pass an interpolated template literal into a function call.

  • The resulting function's first parameter is an array of the strings in the interpolated string.
  • The subsequent parameters are the interpolated values.

Example.

const exampleFunction = (testStringsArray, interpolated1, interpolated2) => console.log(interpolated2, interpolated1, testStringsArray[0])

const value1 = "B"
const value2 = "C"

exampleFunction`A ${value1} ${value2}`

// Result is "C B A"

Enter fullscreen mode Exit fullscreen mode

This might not be something we use day-to-day but it may be quite handy for package builders and possibly creating dynamic CSS values.

The one place that I have seen it used this in is styled components, although this is in hindsight - I didn't realise I was using this feature until I recently learned about what tagged templates were!

Top comments (0)