Template Literals In Depth
Template literals, introduced in ES2015, are string literals delimited by backtick characters. They solve two long-standing pain points in JavaScript: embedding variable values into strings and writing multi-line strings without concatenation or escape sequences.
Expression Interpolation
Inside a template literal, any expression wrapped in ${ } is evaluated and its result is coerced to a string and inserted. This includes arithmetic, method calls, ternary expressions, and even nested template literals.
Multi-line Strings
A template literal preserves newlines and indentation exactly as written in the source file. This makes building HTML snippets or formatted output much cleaner than joining strings with \n.
Tagged Templates
A tagged template is a function call where the function receives the string parts and interpolated values as separate arguments. Tags power libraries like styled-components, GraphQL query builders, and localisation utilities. The tag function can return any value, not just a string.