JavaScript Core/
Lesson

Every codebase you'll work on uses template literals. They replaced the old "Hello, " + name + "!" pattern that made string building feel like assembling furniture without instructions. If you've ever asked an AI to generate JavaScript, you've already seen backtick strings in the output, but understanding how they actually work gives you the ability to spot when the AI generates them poorly.

From concatenation to interpolationWhat is interpolation?Inserting dynamic values like usernames or counts into a text template, replacing placeholders with actual data at display time.

Template literals are enclosed in backticks instead of single or double quotes. The ${} syntax embeds any JavaScript expression directly inside the string.

const name = 'Alice';
const age = 25;

// Old way - string concatenation
const old = 'Hello, ' + name + '! You are ' + age + ' years old.';

// Modern way - template literal
const modern = `Hello, ${name}! You are ${age} years old.`;

The template literal version reads like natural language. No juggling quotes and plus signs, no off-by-one spaces.

What can go inside ${}?

Any valid JavaScript expression evaluates and converts to a string automatically.

Expression typeExampleResult
Variable${name}'Alice'
Math${price * 1.2}'35.988'
Function call${name.toUpperCase()}'ALICE'
Ternary${age >= 18 ? 'adult' : 'minor'}'adult'
Nested template` ${inner ${x}} `Evaluates inner first
const price = 29.99;
const quantity = 3;

const total = `Total: $${(price * quantity).toFixed(2)}`;
// 'Total: $89.97'

const isMember = true;
const message = `Price: $${isMember ? 20 : 35}`;
// 'Price: $20'
AI pitfall
AI tools like Copilot often generate string concatenation ('Hello ' + name) when a template literal would be cleaner and more readable. If you see + joining strings and variables, refactor to backticks. The AI falls back to concatenation because its training data includes older JavaScript patterns, it does not distinguish "old but functional" from "modern best practice."
02

Multi-line strings

Before template literals, multi-line strings required \n escape characters or ugly concatenation chains.

// Old way - hard to read
const oldHtml = '<div>\n' +
  '  <h1>Welcome</h1>\n' +
  '  <p>Thanks for visiting!</p>\n' +
  '</div>';

// Modern way - clean and readable
const newHtml = `
  <div>
    <h1>Welcome</h1>
    <p>Thanks for visiting!</p>
  </div>
`;

What you see is what you get. Line breaks and indentation inside backticks become part of the string. This is especially useful for generating HTML, SQLWhat is sql?A language for querying and managing data in relational databases, letting you insert, read, update, and delete rows across tables. queries, or any formatted text.

Watch out
Indentation inside template literals becomes part of the string. If you indent your template to match your code style, those leading spaces appear in the output. For clean output, either start content at column zero or use a .trim() helper.
03

Tagged templates

You can "tag" a template literal with a function that processes the string pieces and the interpolated values separately. The tag function receives the static string segments as the first argument and each expression result as the remaining arguments.

function highlight(strings, ...values) {
  return strings.reduce((result, string, i) => {
    const value = values[i] !== undefined ? `**${values[i]}**` : '';
    return result + string + value;
  }, '');
}

const price = 29.99;
const discount = 10;

const msg = highlight`Price: $${price} (${discount}% off)`;
// 'Price: $**29.99** (**10**% off)'

Real-world use case: safe SQLWhat is sql?A language for querying and managing data in relational databases, letting you insert, read, update, and delete rows across tables. queries

Tagged templates are used by libraries to sanitize input and prevent injection attacks.

function sql(strings, ...values) {
  const sanitized = values.map(v =>
    typeof v === 'string' ? `'${v.replace(/'/g, "''")}'` : v
  );
  return strings.reduce((query, string, i) => {
    return query + string + (sanitized[i] ?? '');
  }, '');
}

const userId = 42;
const query = sql`SELECT * FROM users WHERE id = ${userId}`;
// "SELECT * FROM users WHERE id = 42"

Libraries like styled-components (CSS-in-JS) and lit-html (HTML templating) are built entirely on tagged templates. Once you understand the mechanism, you'll recognize it everywhere.

04

Common patterns and gotchas

Nesting template literals

Template literals can nest, but readability drops fast:

const items = ['apples', 'bread', 'milk'];
const list = `Shopping list: ${items.map(i => `- ${i}`).join('\n')}`;

For complex nesting, extract the inner expression into a variable first. Your future self will thank you.

Escaping special characters

Use a backslash to include literal backticks or dollar-brace sequences:

const escaped = `Use \`backticks\` and \${} in strings`;
// 'Use `backticks` and ${} in strings'
05

Quick reference

FeatureSyntaxUse case
Basic interpolation` Hello ${name} | Insert variables into strings | | Expression | Total: ${a + b} | Math, logic, function calls | | Multi-line | Backticks with line breaks | HTML, SQL, formatted text | | Tagged template | tagtext ${expr} | Custom string processing, sanitization | | Escape backtick | \ ` | Include literal backtick in string | | Escape dollar-brace | \${ | Include literal ${` in string