Q10 of 40 · JavaScript
What are template literals, and what are tagged templates?
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, "<");
return acc + val + str;
});
}
const name = "<script>";
const html = safe`<p>Hello ${name}</p>`;
// <p>Hello <script></p>// WHAT INTERVIEWERS LOOK FOR
// COMMON PITFALL
// Related questions