ES6+ Modern JavaScript
Tagged Template Literals
Master Tagged Template Literals in JavaScript. Learn to write custom tag functions, escape strings, process values, and understand metaprogramming patterns.
1. Introduction
Tagged Template Literals are an advanced form of template literals. They allow you to parse template literals using a function (a tag function), giving you full control over how string fragments and dynamic variables are combined and formatted.
2. Why It Matters
Tagged templates are widely used in modern libraries (like styled-components or graphql-tag). They allow you to write domain-specific languages (like inline CSS or GraphQL queries) inside JavaScript strings, parsing and escaping variables automatically.
3. Real-World Analogy
Think of a Custom Stamp and Sign Assembly Line:
- Standard Template Literal: Writing a generic message on a template form: "Welcome to [Location]". The browser fills in the blank and prints the result immediately.
- Tagged Template (The Editor Review): Before printing the form, you hand the draft to an editor (the tag function). The editor checks the text parts and the values separately. If the location name is unsafe (e.g. contains scripting code), the editor sanitizes it before printing, ensuring the final output is safe.
4. Tag Functions
A tag function is called with the array of static string fragments as its first argument, followed by the evaluated values of the template expressions:
5. HTML Sanitization
A common use case for tagged templates is automatically escaping dynamic variables inside HTML strings to prevent Cross-Site Scripting (XSS) vulnerabilities:
6. Practical Example
This script demonstrates creating a tagged template that localizes currency values dynamically:
7. Common Mistakes
- Invoking tagged templates with parentheses: Invoking a tag function using standard function call syntax (e.g.
myTag(...)) passes the template as a regular string, which will cause parameter mismatches. Use backticks directly:myTag`template`.
8. Quick Quiz
Q1: What is the first argument passed to a template literal tag function?
A) An array containing the evaluated expression values
B) An array containing the static string fragments of the template
Answer: B — The first parameter is an array of the static string parts. Sibling parameters contain the evaluated values of the template expressions.
9. Scenario-Based Challenge
The Multi-Line SQL Query Builder:
You write a database helper query module. To prevent SQL Injection vulnerabilities, all dynamic variables inside SQL query templates must be replaced with parameter placeholders (like ), and the raw parameters must be returned separately. Write this query builder tag function.
1, 2
10. Debugging Exercise
Explain why this tag function output has missing spaces, and how to fix it:
function badJoin(strings, ...values) {
// Bug: simply joining values forgets to interleave strings!
return strings.join('') + values.join('');
}
const user = 'Alice';
console.log(badJoin`Hello ${user}! Welcome.`); // logs "Hello ! Welcome.Alice" instead of correct spacing! Why?
View Solution
Diagnosis: The function joins the arrays separately instead of interleaving the static string fragments and dynamic values in order. This results in the string fragments being joined first, followed by all the expression values appended at the end.
Fix: Interleave the arrays by iterating over the strings and placing each value in between them using a reduce loop:
function correctJoin(strings, ...values) {
return strings.reduce((acc, str, i) => {
return acc + (values[i - 1] || '') + str;
});
}
11. Interview Questions
🟢 Q1: Describe tagged template literals and explain how they are used in libraries like styled-components.
Answer: Tagged template literals allow you to parse templates using a tag function. The tag function receives the static string parts and the evaluated expression values separately.
Libraries like styled-components use this to write CSS styles directly inside JavaScript strings. The tag function parses the styles, processes dynamic variables (like theme settings passed as props), generates a unique CSS class name, and registers the style sheet in the document head dynamically.
12. Production Considerations
- • Caching Templates: The array of static string parts passed to a tag function is frozen by the engine. The browser passes the exact same array reference on subsequent executions, allowing you to cache template parsing results and improve performance in production.