JavaScript: Template Literals and Tagged Templates
Before ES6, string concatenation in JavaScript was notoriously ugly and prone to errors, heavily relying on the + operator and awkward escape characters for newlines.
ES6 introduced Template Literals (enclosed in backticks `), solving these problems and adding advanced meta-programming capabilities.
1. String Interpolation
The most common use case for template literals is embedding expressions directly inside a string. Using the ${expression} syntax, JavaScript evaluates the inner code and converts it to a string seamlessly.
// Pre-ES6 Concatenation
var name = "Alice";
var age = 25;
var oldGreeting = "Hello, my name is " + name + " and I am " + age + " years old.";
// ES6 Template Literal
const newGreeting = `Hello, my name is ${name} and I am ${age} years old.`;You can execute any valid JavaScript expression inside the placeholder:
const price = 10;
const tax = 0.2;
console.log(`Total cost: $${price + (price * tax)}`);
// Output: Total cost: $12
console.log(`Status: ${age >= 18 ? 'Adult' : 'Minor'}`);
// Output: Status: Adult2. Multiline Strings
Before ES6, creating strings that span multiple lines required appending \n characters and concatenating strings across lines. Template literals respect literal line breaks exactly as they are written in the code.
// Pre-ES6
var text = "This is line 1.\n" +
"This is line 2.";
// ES6 Template Literal
const modernText = `This is line 1.
This is line 2.`;This is incredibly useful when writing raw HTML templates or SQL queries directly in JavaScript files.
3. Tagged Templates (Advanced)
A lesser-known but highly powerful feature is Tagged Templates. A "tag" is simply a function that parses a template literal.
When you place a function name immediately before a template literal, JavaScript parses the literal into chunks and passes those chunks into the function as arguments.
How it works:
function highlight(strings, ...values) {
// 'strings' is an array of the raw text blocks: ["My name is ", " and I am ", " years old."]
// 'values' is an array of the evaluated expressions: ["Alice", 25]
let result = "";
strings.forEach((str, i) => {
result += str + (values[i] ? `<b>${values[i]}</b>` : "");
});
return result;
}
const name = "Alice";
const age = 25;
// Notice there are no parentheses calling the function!
const html = highlight`My name is ${name} and I am ${age} years old.`;
console.log(html);
// Output: "My name is <b>Alice</b> and I am <b>25</b> years old."Where have you seen this?
If you've ever used the popular styled-components library in React, or written GraphQL queries using gql, you've used Tagged Templates!
// styled-components uses tagged templates to parse CSS
const Button = styled.button`
background: ${props => props.primary ? 'blue' : 'white'};
color: black;
`;Senior-Level Interview Answer
Template literals provide syntactic sugar for string interpolation and multiline strings using backticks, completely replacing cumbersome concatenation operators. Beyond basic formatting, they support Tagged Templates, a powerful metaprogramming feature that allows a custom parser function to intercept the string literals and interpolated expressions. This allows developers to safely escape inputs, localize strings, or construct complex domain-specific languages (DSLs) natively within JavaScript, as seen in libraries like
styled-componentsorapollo-client.
Common Interview Mistakes
❌ Forgetting that Template Literals execute arbitrary code
Because ${} accepts any expression, if you interpolate untrusted user input directly into a template literal used to generate DOM elements (e.g., element.innerHTML = \
$
``), you are exposing your application to Cross-Site Scripting (XSS) attacks. Always sanitize user input or rely on frameworks like React that escape interpolation automatically.