- Home
- Interview Questions
- JavaScript
- 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
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. Instrings,\nbecomes a newline. Instrings.raw, it stays as a backslash followed byn.
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
stringsarray 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.rawis a tag that joins the raw segments with the values. SoString.raw`C:\new\temp`keeps the backslashes, which helps with Windows paths and regex sources. - Since ES2018, an invalid escape sequence such as
\unicodeis allowed inside a tagged template. The cooked value at that position becomesundefinedand onlyrawkeeps 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, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
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, <img src=x onerror=alert(1)>!</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.lengthisvalues.length + 1. This leads to off-by-one bugs or anundefinedbeing 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
stringsandstrings.raw, and how doesString.rawuse it? - How could a library use the identity of the
stringsarray 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
- How do HttpOnly, Secure and SameSite cookie flags protect against XSS and CSRF? · 1 ans
- Why can't try/catch catch an error thrown inside a setTimeout callback or a promise? · 1 ans
- What is the temporal dead zone, and are let and const actually hoisted? · 1 ans
- Why is using await inside a loop often slow, and how do you run async tasks in parallel? · 1 ans
Related Questions
- Why can you call a function declaration before it is defined but not a function expression? · JavaScript · 1 ans
- How do try, catch and finally work, and what happens if finally contains a return? · JavaScript · 1 ans
- Why can't try/catch catch an error thrown inside a setTimeout callback or a promise? · JavaScript · 1 ans
- What is the difference between localStorage, sessionStorage and cookies in the browser? · JavaScript · 1 ans
- How do HttpOnly, Secure and SameSite cookie flags protect against XSS and CSRF? · JavaScript · 1 ans
- What is the temporal dead zone, and are let and const actually hoisted? · JavaScript · 1 ans
- Why does a for loop with var and setTimeout print the same value every time? · JavaScript · 1 ans
- Why is using await inside a loop often slow, and how do you run async tasks in parallel? · JavaScript · 1 ans
🙋 Was this asked in your interview?
Which company? (optional — adds this question to the company's page)