Q10 of 40 · JavaScript

What are template literals, and what are tagged templates?

JavaScriptJuniorjavascripttemplate-literalstagged-templateses6strings

Short answer

Short answer: Template literals use backtick delimiters and support `${expr}` interpolation and multi-line strings without escape sequences. Tagged templates prefix a template literal with a function that receives the string parts and interpolated values, enabling DSLs like GraphQL `gql`, SQL builders, and styled-components.

Detail

Template literals (ES6) replace many uses of string concatenation with a cleaner, more readable syntax.

Basic features: Embed any expression with ${...}, write multi-line strings without \n, and nest quotes without escaping.

Tagged templates: A tag is a function called with the literal string parts as an array and the interpolated values as subsequent arguments. The tag can return anything — not necessarily a string. This is how libraries like gql (GraphQL), sql (Postgres queries), and styled-components work.

In test automation: Template literals are everywhere in Playwright selectors, assertion messages, and URL builders. Tagged templates appear in some test helpers for building fixture strings or assertion DSLs programmatically.

// EXAMPLE

// Basic interpolation
const user = "Alice";
const msg = `Hello, ${user}! Today is ${new Date().toDateString()}`;

// Multi-line (no \n needed)
const query = `
  SELECT *
  FROM users
  WHERE id = ${userId}
`;

// Tagged template — escape HTML in interpolated values
function safe(strings, ...values) {
  return strings.raw.reduce((acc, str, i) => {
    const val = String(values[i - 1] ?? "").replace(/</g, "&lt;");
    return acc + val + str;
  });
}
const name = "<script>";
const html = safe`<p>Hello ${name}</p>`;
// <p>Hello &lt;script></p>

// WHAT INTERVIEWERS LOOK FOR

Comfort with interpolation and multi-line strings is baseline. Tagged templates separate candidates who have worked with GraphQL clients, CSS-in-JS, or SQL builders. Understanding what the tag function receives (parts array + values) shows depth.

// COMMON PITFALL

Forgetting that template literal expressions are evaluated eagerly — there is no lazy evaluation unless you wrap in a function. Multi-line literals include the newlines literally, including leading whitespace.