Tagged Templates
Medium — good to knowFrontend
ELI5 — The Vibe Check
Tagged Templates are template literals with a function stuck in front of them. The function receives the string parts and interpolated values separately, so it can do custom processing. It's how styled-components and GraphQL queries work their magic — html<div> isn't just a string.
Real Talk
Tagged template literals are a JavaScript feature where a function (the tag) is called with the template's string segments and interpolated values as separate arguments. This enables custom string processing for use cases like CSS-in-JS (styled-components), SQL query builders, and internationalization libraries.
Show Me The Code
function highlight(strings, ...values) {
return strings.reduce((result, str, i) => {
return result + str + (values[i] ? `<mark>${values[i]}</mark>` : '');
}, '');
}
const name = 'World';
highlight`Hello ${name}!`; // "Hello <mark>World</mark>!"
When You'll Hear This
"styled-components uses tagged templates to parse CSS from template literals" / "Tagged templates are the magic behind graphqlquery { user { name } }"