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!

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

Cloudinary image

Zoom pan, gen fill, restore, overlay, upscale, crop, resize...

Chain advanced transformations through a set of image and video APIs while optimizing assets by 90%.

Explore

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay