JavaScript Interview Prep
ES6+ Features

Template Literals

Backticks, Interpolation, and Tagged Superpowers

LinkedIn Hook

You write "Hello " + name + ", you have " + count + " messages." in a pull request.

The senior engineer comments: "Template literal, please."

You switch to backticks. They follow up: "Can you also sanitize SQL with them?"

Silence.

Template literals are the most "obvious" ES6 feature — and also the most underused. Everyone knows ${name} interpolation. Almost nobody uses tagged templates to prevent SQL injection, build CSS-in-JS, or ship an i18n layer in 5 lines of code.

In this lesson I unpack what backticks actually are, why String.raw matters for Windows paths and regex, and how tagged templates turn strings into a tiny DSL.

If you still reach for + to concatenate — this lesson will retire that habit.

Read the full lesson -> [link]

#JavaScript #InterviewPrep #ES6 #TemplateLiterals #Frontend #CodingInterview #WebDevelopment


Template Literals thumbnail


What You'll Learn

  • Backtick syntax with ${} interpolation and native multi-line support
  • Tagged templates — turning a template literal into a function call for SQL, CSS, and i18n
  • When to reach for String.raw instead of escaping yourself into a corner

Basic Syntax and Interpolation

Before ES6, string concatenation was painful. You'd write "Hello " + name + ", you are " + age + " years old." — ugly, error-prone, and impossible to read at scale. Template literals fix all of that, and they go far beyond simple interpolation.

Template literals use backticks (`) instead of quotes, and ${} for embedding expressions.

const name = "Rakibul";
const age = 25;

// Old way
const old = "Hello " + name + ", you are " + age + " years old.";

// Template literal
const modern = `Hello ${name}, you are ${age} years old.`;

// Any expression works inside ${}
const msg = `Next year you'll be ${age + 1}`;
const cond = `Status: ${age >= 18 ? "adult" : "minor"}`;
const call = `Upper: ${name.toUpperCase()}`;

Multi-line Strings

// Old way — manual \n
const oldHtml = "<div>\n  <h1>Title</h1>\n  <p>Content</p>\n</div>";

// Template literal — natural line breaks
const html = `
<div>
  <h1>Title</h1>
  <p>Content</p>
</div>
`;

Tagged Templates — The Real Power

A tagged template is a function that processes a template literal. The function receives the string parts and the interpolated values separately — giving you full control over how the string is assembled.

function highlight(strings, ...values) {
  // strings: array of static string parts
  // values: array of interpolated expressions
  return strings.reduce((result, str, i) => {
    return result + str + (values[i] !== undefined ? `<mark>${values[i]}</mark>` : "");
  }, "");
}

const name = "Rakibul";
const role = "developer";

const output = highlight`My name is ${name} and I'm a ${role}`;
// "My name is <mark>Rakibul</mark> and I'm a <mark>developer</mark>"

Tagged Template for SQL Sanitization

This is a real-world pattern used in libraries like sql-template-strings:

function sql(strings, ...values) {
  const sanitized = values.map(val => {
    if (typeof val === "string") return `'${val.replace(/'/g, "''")}'`;
    if (val === null) return "NULL";
    return String(val);
  });

  return strings.reduce((query, str, i) => {
    return query + str + (sanitized[i] || "");
  }, "");
}

const userInput = "Robert'; DROP TABLE users; --";
const id = 42;

const query = sql`SELECT * FROM users WHERE name = ${userInput} AND id = ${id}`;
// "SELECT * FROM users WHERE name = 'Robert''; DROP TABLE users; --' AND id = 42"
// The single quote is escaped — SQL injection prevented

Practical Tagged Template Uses

// CSS-in-JS (styled-components pattern)
function css(strings, ...values) {
  return strings.reduce((result, str, i) => result + str + (values[i] || ""), "");
}
const color = "red";
const style = css`color: ${color}; font-size: 16px;`;

// i18n (internationalization)
function i18n(strings, ...values) {
  const template = strings.join("{}");
  const translated = translations[template] || template;
  return values.reduce((result, val) => result.replace("{}", val), translated);
}

Raw Strings

String.raw is a built-in tagged template that returns the raw string without processing escape sequences:

console.log(`Line1\nLine2`);
// Line1
// Line2

console.log(String.raw`Line1\nLine2`);
// "Line1\nLine2" — the \n is literal, not a newline

// Useful for regex and file paths
const path = String.raw`C:\Users\Rakibul\Documents`;
const regex = String.raw`\d+\.\d+`;

Template Literals visual 1


Common Mistakes

  • Using template literals everywhere, even for simple constant strings — the backtick tax is zero at runtime, but it makes diffs noisier and hurts scanability for pure literals with no interpolation.
  • Forgetting that ${} evaluates any expression — calling a function inside a template literal runs it every time the string is built, which can be surprisingly expensive in loops.
  • Expecting String.raw to disable all escapes — it only stops the literal's own backslash processing. Unicode escapes inside ${} expressions still run, and \u sequences in the raw text are left as literal characters.

Interview Questions

Q: What are template literals and how do they differ from regular strings?

Template literals use backticks, support expression interpolation via ${}, allow multi-line strings without \n, and can be "tagged" with a function for custom processing. Regular strings (single/double quotes) support none of these.

Q: What is a tagged template literal? Give a practical use case.

A tagged template is a function called with a template literal. The function receives the static string parts and interpolated values as separate arguments. Practical uses: SQL sanitization (preventing injection), CSS-in-JS (styled-components), i18n translation, and HTML escaping.

Q: What does String.raw do?

String.raw is a built-in tag function that returns the raw string content without processing escape sequences like \n, \t, etc. It's useful for regex patterns, Windows file paths, and LaTeX strings.

Q: Write a Set-style tag that HTML-escapes every interpolated value.

Implement a tag function that receives (strings, ...values), maps each value through an escape routine that replaces &, <, >, ", ' with HTML entities, then zips strings and the sanitized values back together with reduce. This is the core idea behind libraries like lit-html's safe interpolation.


Quick Reference — Cheat Sheet

TEMPLATE LITERALS — QUICK MAP

Syntax:
  `text ${expr} text`         -> interpolation
  `multi                       -> multi-line (real newlines)
   line`
  tag`text ${x} text`          -> tagged template
  String.raw`\n`               -> raw (no escape processing)

Tag function signature:
  function tag(strings, ...values) { ... }
    strings  -> array of static parts (length = values.length + 1)
    values   -> array of interpolated expressions

Common patterns:
  - SQL sanitization    (escape single quotes on every value)
  - CSS-in-JS           (styled-components, emotion)
  - i18n translation    (replace placeholders)
  - HTML escaping       (lit-html, safe rendering)
  - Windows paths + regex via String.raw

Previous: Symbol and BigInt -> New Primitives Next: Arrow Functions -> Lexical this and Shorter Syntax


This is Lesson 9.1 of the JavaScript Interview Prep Course — 14 chapters, 87 lessons.

On this page