Template literals provide powerful string interpolation and multi-line strings with backtick syntax.
Basic Syntax#
Multi-line Strings#
Nested Templates#
Tagged Templates#
HTML Escaping#
CSS-in-JS Pattern#
SQL Query Builder#
Internationalization#
Debug Logging#
Regular Expressions#
String.raw#
Best Practices#
Basic Usage:
✓ Use for string interpolation
✓ Use for multi-line strings
✓ Use for HTML/SQL templates
✓ Trim when whitespace matters
Tagged Templates:
✓ Use for escaping (HTML, SQL)
✓ Use for DSLs (CSS-in-JS)
✓ Use for i18n
✓ Document tag function behavior
Performance:
✓ Tagged templates are cached
✓ Avoid complex logic in interpolations
✓ Use for clarity, not everywhere
✓ Consider template caching for repeated use
Avoid:
✗ Overusing for simple strings
✗ Deep nesting without reason
✗ Forgetting to escape user input
✗ Complex expressions in ${}
Conclusion#
Template literals simplify string interpolation with ${} syntax and enable multi-line strings. Tagged templates unlock powerful patterns like HTML escaping, CSS-in-JS, SQL query builders, and i18n. Use String.raw when you need literal backslashes. Always escape user input in HTML contexts to prevent XSS vulnerabilities.