Trap #1: XSS Injection from Unescaped HTML Interpolation
Interpolating untrusted user input directly into HTML strings via template literals opens severe Cross-Site Scripting (XSS) holes. Use a tagged sanitizer function.
Trap #2: Unintended Whitespace in Multi-Line Templates
Indentation tabs and line breaks are captured literally. Pre-formatting code or SQL queries with template literals can include dozens of unwanted leading spaces.
Trap #3: Objects Coerced to [object Object]
Interpolating an object (`User: ${user}`) calls user.toString(), outputting User: [object Object]. Use JSON.stringify(user).
Trap #4: Tagged Template Parameter Count Mismatch
In tagged templates, the strings array always has exactly one more element than the values array: strings.length === values.length + 1.
Trap #5: String.raw vs Standard String Escapes
Standard template literals parse escape sequences (\n becomes a newline). Use String.raw`C:\path\new` to keep escape characters intact.
💬 Frequently Asked Questions
What is a tagged template literal in JavaScript?
A tagged template is a function call where template literals are parsed and passed as arguments (strings array and interpolated values), enabling custom parsing like GraphQL queries or CSS-in-JS.
What does String.raw do?
String.raw is a built-in tag function that returns raw string contents without interpreting backslash escape sequences (e.g. \n remains literal \n).
Can expressions inside ${} call functions and perform math?
Yes, any valid JavaScript expression (arithmetic, function calls, ternaries) can be evaluated inside ${}.
How do tagged template literals prevent SQL injection in libraries?
Database libraries inspect the raw strings and values separately, automatically converting interpolated values into parameterized SQL placeholders ($1, $2).
Can you nest template literals inside other template literals?
Yes, template literals can be nested inside ${} expressions, useful for conditional formatting.