What are template literals and how do you use them?
Advertisement
🧩 Scenario
Architecture Walkthrough
Interpolation and Multi-line Strings
Template literals use backticks instead of single or double quotes. Any expression placed inside ${} is evaluated and converted to a string using the value's toString() method. This covers simple variables, arithmetic, ternary operators, and even function calls.
Multi-line strings are a direct benefit of the backtick syntax. Without template literals, creating a multi-line string required string concatenation with \n escape characters. With template literals, you simply press Enter inside the backticks and the newline is included in the string. The whitespace at the start of each line is literal, so indentation matters.
Expressions Inside Interpolation
The ${} delimiter evaluates any valid JavaScript expression. This includes method calls (${arr.join(', ')}), ternaries (${isLoggedIn ? 'Welcome' : 'Please sign in'}), and nested template literals. However, embedding complex logic directly inside a string makes the code difficult to read and test.
The best practice is to keep the expression inside ${} as simple as a variable reference or a short ternary. If the logic is complex, compute the value in a variable first and interpolate the variable. This keeps the string readable and the logic testable.
Tagged Template Literals
Tagged template literals are a lesser-known but powerful feature. A tag is a function that receives the string parts and the interpolated values as separate arguments. The tag function can process them in any way before returning a result.
Common use cases for tagged templates include: sanitizing HTML to prevent XSS injection, formatting currency or dates consistently, building SQL query builders that safely parameterize values, and internationalization libraries that translate strings at runtime. Libraries like styled-components and graphql use tagged templates extensively to provide their syntax.
Key Code Explained
const name = 'Ghazi';
const role = 'Engineer';
// Basic interpolation
const greeting = `Hello, my name is ${name} and I am a ${role}.`;
// Expression inside interpolation
const score = 87;
const message = `Result: ${score >= 90 ? 'A' : score >= 70 ? 'B' : 'C'}`;
// Multi-line string
const html = `
<div class="card">
<h2>${name}</h2>
<p>${role}</p>
</div>
`;
// Object inserted directly: avoid this
const user = { name: 'Ali', age: 25 };
console.log(`User: ${user}`); // "User: [object Object]" — almost never what you want
console.log(`User: ${user.name}, Age: ${user.age}`); // correct approach
// Tagged template literal
function highlight(strings, ...values) {
return strings.reduce((result, str, i) => {
return result + str + (values[i] !== undefined ? `<strong>${values[i]}</strong>` : '');
}, '');
}
const product = 'keyboard';
const price = 49;
const promo = highlight`The ${product} costs $${price} today.`;
// "The <strong>keyboard</strong> costs $<strong>49</strong> today."
The tagged template example shows how the tag function receives the string parts and values separately, allowing it to wrap each interpolated value in HTML before reassembling the string. This is how libraries achieve CSS-in-JS syntax and safe SQL parameterization.
Tradeoffs
| Approach | Pro | Con |
|---|---|---|
| Template literals | Readable, multi-line, expression support | Backtick may need escaping in nested cases, less familiar to some |
| String concatenation (+) | Works in all environments, familiar | Verbose and error-prone with multiple variables |
| Array.join() | Good for repeated patterns like list items | Verbose for one-off strings with mixed content |
What Interviewers Actually Check
- Whether you know the correct syntax (backticks, not quotes)
- Whether you can use expressions, not just variables, inside
${} - Whether you know what happens when an object is inserted directly into a template string
- Whether you know tagged template literals exist and can name one use case
- Whether you would keep interpolated expressions simple or compute them outside the string
Follow-Up Questions
- How would you safely escape a user-provided string before inserting it into a template literal that builds HTML?
- What does
String.rawdo, and when would you use it? - If a template literal contains a function call that throws, when does the error occur?
- How do libraries like
styled-componentsuse tagged templates to achieve CSS-in-JS syntax? - A PR uses complex nested ternaries inside
${}across multiple lines. What feedback would you leave?
Common Candidate Mistakes
- Using single or double quotes instead of backticks and getting a syntax error
- Inserting a plain object with
${obj}and being confused by[object Object]in the output - Embedding complex multi-step logic directly inside
${}instead of computing a named variable first - Not knowing that tagged template literals are a language feature, thinking all template syntax comes from libraries
- Forgetting that newlines inside a backtick string are literal, which affects how the string renders
Interview Readiness Checklist
Before you leave this question, make sure you can answer:
- Can you write a multi-line string with interpolated variables using template literals?
- Can you embed a ternary expression or a function call inside
${}? - Can you explain what a tagged template literal is and give one real-world use case?
- Can you predict what happens when you insert an object directly into a template string?
- Can you compare readability between concatenation and template literals for a multi-variable string?
Summary
Template literals replace quoted strings with backtick strings, adding two key capabilities: string interpolation via ${} and native multi-line support. Any JavaScript expression can go inside ${}, and the result is coerced to a string. This makes template literals the standard tool for building strings that include variables, computed values, or conditional content.
Tagged template literals extend the syntax further by letting a function intercept the string parts and values before assembly. This powers CSS-in-JS libraries, safe SQL parameterization, HTML sanitization, and internationalization, all using familiar string syntax.
The practical rule is to use template literals whenever a string contains at least one dynamic value, and to keep the expressions inside ${} as simple as possible, computing complex logic in named variables before the string is constructed.
Can I use expressions in template literals?
Yes, anything inside ${} is evaluated as a JavaScript expression.
Advertisement
Stay Updated
Get the latest frontend challenges, interview questions and tutorials delivered to your inbox.
Advertisement