1. Home
  2. Interview Questions
  3. JavaScript
  4. What are tagged template literals in JavaScript and when wou…

Try answering first

In a real interview nobody shows you the answer. Think it through (or type it), then reveal the answers and rate yourself.

1 Answer

0 0
InterviewQuestions Team ✔ Expert answer ✔ Best answer ·

Short answer: A tagged template is a function call written as tag`text ${value}`. The function receives an array of the literal string parts plus the interpolated values as separate arguments, so it can process them before combining them. This makes it useful for safe HTML escaping, SQL or GraphQL helpers, CSS-in-JS and reading raw strings.

Detailed explanation

A normal template literal evaluates every ${} expression, converts each result to a string and joins everything immediately. When you put a function name directly before the backtick, JavaScript does not build the string. It calls the function with the pieces instead:

  • First argument (strings): an array of the static text segments. It always has exactly one more element than the number of values. If the template starts or ends with an interpolation, the first or last segment is an empty string.
  • Remaining arguments (...values): the evaluated results of each ${} expression, in order. They are passed as they are, not converted to strings. You get the actual objects, numbers or functions.
  • strings.raw: a parallel array containing the text exactly as typed, with escape sequences left unprocessed. In strings, \n becomes a newline. In strings.raw, it stays as a backslash followed by n.

A few details that experienced candidates are expected to know:

  • The tag can return anything, not only a string. It can return a DOM node, a query object, a parsed AST or a function.
  • The strings array is frozen. The same array object is reused every time that particular call site runs. Libraries use this identity as a cache key, for example to parse a template only once.
  • The built-in String.raw is a tag that joins the raw segments with the values. So String.raw`C:\new\temp` keeps the backslashes, which helps with Windows paths and regex sources.
  • Since ES2018, an invalid escape sequence such as \unicode is allowed inside a tagged template. The cooked value at that position becomes undefined and only raw keeps the text. In an untagged template, the same input is a SyntaxError.

Real-world uses include escaping user input in HTML (lit-html), styled-components and Emotion for CSS, gql for GraphQL, and SQL libraries that turn interpolations into bound parameters instead of string concatenation.

Example

function inspect(strings, ...values) {
  console.log(strings);      // ['Total: ', ' items, ', '\n']
  console.log(strings.raw);  // ['Total: ', ' items, ', '\\n']
  console.log(values);       // [3, true]
}
inspect`Total: ${3} items, ${true}\n`;

// Practical: escape interpolated values, trust the static markup
const escapeHtml = s => String(s)
  .replace(/&/g, '&')
  .replace(/</g, '&lt;')
  .replace(/>/g, '&gt;')
  .replace(/"/g, '&quot;')
  .replace(/'/g, '&#39;');

function html(strings, ...values) {
  return strings.reduce((out, str, i) =>
    out + str + (i < values.length ? escapeHtml(values[i]) : ''), '');
}

const name = '<img src=x onerror=alert(1)>';
console.log(html`<p>Hello, ${name}!</p>`);
// <p>Hello, &lt;img src=x onerror=alert(1)&gt;!</p>

The static parts written by the developer are trusted. Only the dynamic values are escaped, and that is exactly the split a tag function gives you.

Common mistakes

  • Thinking the tag receives one finished string. It receives the segments and the values separately, before any joining happens.
  • Forgetting that strings.length is values.length + 1. This leads to off-by-one bugs or an undefined being appended at the end.
  • Writing tag(`...${x}`) with parentheses. That passes one already-built string to an ordinary function, so the tagging behaviour is lost.
  • Assuming a hand-written escaping tag makes SQL safe. For databases, values should become bound parameters handled by the driver, not escaped text.

Follow-up questions

  • What is the difference between strings and strings.raw, and how does String.raw use it?
  • How could a library use the identity of the strings array to cache parsed templates?
  • How would you write a tag that dedents a multi-line template string?

Interview tip: Write a five-line tag that logs its arguments and point out the empty string segments at the ends. It is the quickest way to show you understand how the call really works.

Reviewed by the Interview Questions editorial team · Last updated

How well did you know this?

Rate yourself to track progress, build your streak and get “didn't know” questions in your revision list.

Your Answer

More hard JavaScript questions

All hard questions →

Related Questions

‹
Q5 of 10 · JavaScript
Next ›

Interview Questions

Free interview questions and answers, MCQ practice, online tests, mock interviews and group discussions — everything you need to crack your next interview.
📍 Dasardot LLC
1309 Coffeen Avenue STE 1200
Sheridan, Wyoming 82801
USA