Hint
A function that processes the template — receives string parts and interpolated values separately
A tagged template is a function placed before a template literal — it receives the string parts and interpolated values separately, allowing custom processing.
function highlight(strings, ...values) {
// strings: ['User ', ' scored ', '%']
// values: ['Alice', 95]
return strings.reduce((result, str, i) =>
result + str + (values[i] !== undefined
? `${values[i]}`
: ''), '');
}
const user = 'Alice', score = 95;
highlight`User ${user} scored ${score}%`;
// 'User Alice scored 95%'
// Real-world uses:
// 1. styled-components
const Button = styled.div`
background: ${props => props.primary ? 'blue' : 'white'};
`;
// 2. SQL sanitization (prevents injection!)
const result = sql`SELECT * FROM users WHERE id = ${userId}`;
// tag function escapes userId before inserting
// 3. GraphQL queries
const query = gql`
query GetUser { user(id: ${id}) { name } }
`;