How to use template literals in JavaScript
· Category: JavaScript
Short answer
Template literals use backticks (`) to embed expressions via ${expression}, support multiline text, and enable tagged templates for custom processing.
Steps
- Interpolate variables and expressions:
javascript const name = 'Leo'; const greeting = `Hello, ${name}!`; - Write multiline strings without escape characters:
javascript const html = ` <div> <p>Content</p> </div> `; - Use tagged templates to transform strings:
javascript function highlight(strings, ...values) { return strings.reduce((acc, s, i) => acc + s + (values[i] || ''), ''); } const msg = highlight`Value is ${42}`;
Tips
- Nest template literals for conditional logic inside interpolation.
- Use
String.rawtagged template to ignore escape sequences.
Common issues
- Forgetting backticks and using regular quotes breaks interpolation.
- Complex expressions inside
${}reduce readability; extract them to variables.