# Template Literals & String Interpolation

> What are template literals in JavaScript, and what do they offer over regular quoted strings?

Canonical: https://www.internhack.in/learn/interview/javascript-interview/js-template-literals
Last updated: 2026-11-28

Difficulty: Beginner

## Question

What are template literals in JavaScript, and what do they offer over regular quoted strings?

## Answer

Template literals are strings written with backticks instead of quotes, introduced in ES2015. They give you three things regular strings lack: interpolation of any expression with `${expression}`, real multi-line strings without `\n`, and tagged templates, where a function receives the pieces of the literal and decides what to build from them.

### Interpolation

Anything inside `${}` is evaluated as a JavaScript expression and converted to a string with the same rules as `String(value)`. That includes arithmetic, ternaries, function calls and property access:

- \`` `Total: Rs ${(paise / 100).toFixed(2)}` `\`
- \`` `Status: ${isPaid ? 'Paid' : 'Pending'}` `\`
- \`` `Hello ${user?.name ?? 'Guest'}` `\`

Compare this with `'Total: Rs ' + (paise / 100).toFixed(2)`. The template version is easier to read, avoids missing spaces, and avoids `+` accidentally doing addition. Objects interpolate as `[object Object]`, so use `JSON.stringify` when you want to see their contents.

### Multi-line strings and indentation

Line breaks inside backticks become part of the string. That makes HTML snippets, SQL and email bodies much cleaner. The catch is indentation: if the literal sits inside indented code, those leading spaces are included. Common fixes are to keep the content flush left, call `.trim()`, or use a `dedent` helper.

### Comparison with quoted strings

| Feature | `'single'` / `"double"` | \`` `template` `\` |
| --- | --- | --- |
| Interpolation | Concatenation with `+` | `${expr}` |
| Multi-line | `\n` escapes | Literal line breaks |
| Embedded quotes | Must escape matching quote | Both ' and " are free; escape backticks |
| Tag functions | No | Yes |
| Performance | Same in practice | Same in practice |

### Tagged templates and String.raw

Writing `tag` directly before the backtick calls `tag(strings, ...values)`. `strings` is an array of the literal pieces (with a `.raw` property holding the unprocessed text) and `values` are the evaluated expressions. Libraries use this for SQL parameterisation, CSS-in-JS (styled-components) and GraphQL (`gql`). The built-in `String.raw` tag returns the text with escape sequences untouched, so \`` String.raw`\\d+\\.\\d+` `\` keeps the backslashes, handy for regex sources and Windows paths.

### Security: interpolation is not escaping

A template literal does not sanitise anything. \`` el.innerHTML = `<p>${comment}</p>` `` with user input is an XSS hole, and `` `SELECT \* FROM users WHERE id = ${id}` `` passed straight to a database is SQL injection. Use `textContent`, a framework that escapes by default (React does for text), or parameterised queries (`$1` placeholders in `pg\`, or a tagged-template SQL library that turns values into parameters).

**How a template literal is built. Change name and count under Tweak to watch the ternary pick message or messages.**

1. **Split**: Fixed string pieces and ${} expressions.
2. **Evaluate**: Each expression runs: variables, ternaries, any expression.
3. **Join**: Values are stringified and joined into one string.

## Code examples

### Interpolation and multi-line strings

```
const order = { id: 'FK-8821', items: 3, paise: 129900, paid: false };

const summary = `Order ${order.id}
Items: ${order.items}
Amount: Rs ${(order.paise / 100).toFixed(2)}
Status: ${order.paid ? 'Paid' : 'Payment pending'}`;
console.log(summary);

console.log(`Object: ${{ a: 1 }}`);
console.log(`JSON: ${JSON.stringify({ a: 1 })}`);
```

Each ${} is a full expression. Plain objects stringify as \[object Object\], so serialise them explicitly.

### How a tag function sees the literal

```
function inspect(strings, ...values) {
  console.log(strings);       // static parts
  console.log(strings.raw);   // unprocessed text
  console.log(values);        // evaluated expressions
  return 'tags can return anything';
}

const city = 'Hyderabad';
const result = inspect`Deliver to ${city}\n in ${30} mins`;
console.log(result);
console.log(String.raw`\d+\.\d+`);
```

The tag gets cooked strings, raw strings and values separately. String.raw returns the raw form, keeping backslashes for regex sources.

## Key points

- Backticks enable ${} interpolation of any expression
- Line breaks and indentation inside the literal are kept
- Tag functions receive (strings, ...values) and strings.raw
- String.raw keeps escape sequences as typed
- Interpolation does not escape HTML or SQL; sanitise or parameterise

## Common follow-up questions

- How would you write a tag function that safely builds SQL queries?
- How do styled-components use tagged templates?
- How do you remove leading indentation from a multi-line template literal?
- What is the difference between strings and strings.raw in a tag function?

## Interview tips

- Name all three features: interpolation, multi-line, tagged templates
- Mention the XSS and SQL injection risk; it shows security awareness
- If time allows, sketch a tiny tag function to prove you know the signature

## Concepts covered

Template Literals, String Interpolation, Multiline Strings, Tagged Templates, String.raw

Previous: [Arrow Functions vs Regular Functions](https://www.internhack.in/learn/interview/javascript-interview/js-arrow-functions) · Next: [null vs undefined](https://www.internhack.in/learn/interview/javascript-interview/js-null-undefined) · [All of JavaScript Interview](https://www.internhack.in/learn/interview/javascript-interview)

## More JavaScript Interview questions

- [JSON: parse, stringify & Common Pitfalls](https://www.internhack.in/learn/interview/javascript-interview/js-json-parse-stringify)
- [Closures & Lexical Scope](https://www.internhack.in/learn/interview/javascript-interview/js-closures-interview)
- [Hoisting & Temporal Dead Zone](https://www.internhack.in/learn/interview/javascript-interview/js-hoisting-interview)
- [Object Methods & Property Descriptors](https://www.internhack.in/learn/interview/javascript-interview/js-object-methods)
- [this Keyword & Binding Rules](https://www.internhack.in/learn/interview/javascript-interview/js-this-keyword)
- [call, apply, bind](https://www.internhack.in/learn/interview/javascript-interview/js-call-apply-bind)

## Related

- [Learn](https://www.internhack.in/learn)
- [Interview Prep](https://www.internhack.in/learn/interview)
- [JavaScript Interview](https://www.internhack.in/learn/interview/javascript-interview)
