Template Literals & String Interpolation

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:

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 `
InterpolationConcatenation with +${expr}
Multi-line\n escapesLiteral line breaks
Embedded quotesMust escape matching quoteBoth ' and " are free; escape backticks
Tag functionsNoYes
PerformanceSame in practiceSame 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

Common follow-up questions

Interview tips

Concepts covered

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

More JavaScript Interview questions