Template literals, introduced in ES6, revolutionized how we work with strings in JavaScript. They use backticks (`) instead of single or double quotes.
1. Multi-line Strings
Traditionally, multi-line strings required \n or string concatenation. With template literals, the whitespace and newlines are preserved exactly as written:
2. Expression Interpolation
You can embed any valid JavaScript expression inside a template literal using ${expression}. This is much more readable than concatenation.
3. Tagged Templates
Tagged templates allow you to call a function to process a template literal. The function receives an array of string literals and the evaluated expressions as arguments.
4. Use Case: SQL Builders
Tagged templates are powerful for creating Domain Specific Languages (DSLs). A common use case is a SQL tag that automatically escapes inputs to prevent SQL injection.