javascript-today

Template Literals

Template literals (also called template strings) provide an easy way to create strings that include variables and expressions. They’re cleaner and more readable than traditional string concatenation.

What are Template Literals?

Template literals use backticks ` instead of quotes and allow embedded expressions with ${}:

// Old way - concatenation
const name = 'Alice';
const greeting = 'Hello, ' + name + '!';
console.log(greeting);  // Hello, Alice!

// Modern way - template literal
const name = 'Alice';
const greeting = `Hello, ${name}!`;
console.log(greeting);  // Hello, Alice!

Key features:

  • Use backticks: `
  • Embed variables: ${variable}
  • Multi-line strings (no \n needed)
  • Evaluate expressions: ${2 + 2}

Basic String Interpolation

Simple Variables

const firstName = 'Bob';
const lastName = 'Smith';
const age = 25;

// Template literal
const intro = `My name is ${firstName} ${lastName} and I'm ${age} years old.`;
console.log(intro);
// My name is Bob Smith and I'm 25 years old.

// Compare with concatenation (messy!)
const intro2 = 'My name is ' + firstName + ' ' + lastName + ' and I\'m ' + age + ' years old.';

Multiple Interpolations

const product = 'Laptop';
const price = 999.99;
const quantity = 2;

const summary = `Item: ${product}, Price: $${price}, Quantity: ${quantity}`;
console.log(summary);
// Item: Laptop, Price: $999.99, Quantity: 2

Expression Evaluation

Template literals can evaluate any JavaScript expression:

Arithmetic

const a = 10;
const b = 5;

console.log(`${a} + ${b} = ${a + b}`);        // 10 + 5 = 15
console.log(`${a} * ${b} = ${a * b}`);        // 10 * 5 = 50
console.log(`${a} divided by ${b} = ${a / b}`);  // 10 divided by 5 = 2

Calculations

const price = 29.99;
const quantity = 3;
const taxRate = 0.08;

const subtotal = price * quantity;
const tax = subtotal * taxRate;
const total = subtotal + tax;

console.log(`Subtotal: $${subtotal.toFixed(2)}`);  // Subtotal: $89.97
console.log(`Tax: $${tax.toFixed(2)}`);            // Tax: $7.20
console.log(`Total: $${total.toFixed(2)}`);        // Total: $97.17

// Or calculate inline
console.log(`Total: $${(price * quantity * (1 + taxRate)).toFixed(2)}`);

Function Calls

function getGreeting(hour) {
  if (hour < 12) return 'Good morning';
  if (hour < 18) return 'Good afternoon';
  return 'Good evening';
}

const hour = 14;
const name = 'Alice';

console.log(`${getGreeting(hour)}, ${name}!`);
// Good afternoon, Alice!

Conditional (Ternary) Operator

const age = 17;
const status = `You are ${age >= 18 ? 'an adult' : 'a minor'}`;
console.log(status);  // You are a minor

const score = 85;
const grade = `Your grade: ${score >= 90 ? 'A' : score >= 80 ? 'B' : score >= 70 ? 'C' : 'F'}`;
console.log(grade);  // Your grade: B

const items = 5;
console.log(`You have ${items} item${items !== 1 ? 's' : ''}`);
// You have 5 items

Multi-line Strings

Template literals preserve line breaks - no need for \n:

Basic Multi-line

// Old way
const message = 'Line 1\nLine 2\nLine 3';
console.log(message);

// New way - much cleaner
const message = `Line 1
Line 2
Line 3`;
console.log(message);

// Output (same):
// Line 1
// Line 2
// Line 3

HTML Templates

const title = 'Welcome';
const content = 'This is the main content area.';

const html = `
  <div class="card">
    <h2>${title}</h2>
    <p>${content}</p>
  </div>
`;

console.log(html);
// Output:
// <div class="card">
//   <h2>Welcome</h2>
//   <p>This is the main content area.</p>
// </div>

SQL Queries

const tableName = 'users';
const userId = 42;

const query = `
  SELECT *
  FROM ${tableName}
  WHERE id = ${userId}
  ORDER BY created_at DESC
  LIMIT 10
`;

console.log(query);

Email Templates

const username = 'alice';
const orderNumber = 'ORD-12345';
const total = 99.99;

const email = `
Hi ${username},

Thank you for your order!

Order Number: ${orderNumber}
Total: $${total}

Your items will ship within 2-3 business days.

Best regards,
The Team
`;

console.log(email);

Nested Templates

You can nest template literals inside each other:

const users = ['Alice', 'Bob', 'Charlie'];

const userList = `
  <ul>
    ${users.map(user => `<li>${user}</li>`).join('')}
  </ul>
`;

console.log(userList);
// Output:
// <ul>
//   <li>Alice</li><li>Bob</li><li>Charlie</li>
// </ul>

Practical Example: Table Rows

const products = [
  { name: 'Laptop', price: 999 },
  { name: 'Mouse', price: 29 },
  { name: 'Keyboard', price: 79 }
];

const table = `
  <table>
    <thead>
      <tr>
        <th>Product</th>
        <th>Price</th>
      </tr>
    </thead>
    <tbody>
      ${products.map(p => `
        <tr>
          <td>${p.name}</td>
          <td>$${p.price}</td>
        </tr>
      `).join('')}
    </tbody>
  </table>
`;

Escaping Backticks

To include a literal backtick in a template literal, escape it with \:

const code = `Use backticks \` for template literals`;
console.log(code);
// Use backticks ` for template literals

const example = `To embed a variable, use \${variable}`;
console.log(example);
// To embed a variable, use ${variable}

Common Patterns

1. Dynamic URLs

const userId = 123;
const endpoint = 'users';

const url = `https://api.example.com/${endpoint}/${userId}`;
console.log(url);
// https://api.example.com/users/123

const page = 2;
const limit = 20;
const searchUrl = `https://api.example.com/search?page=${page}&limit=${limit}`;
console.log(searchUrl);
// https://api.example.com/search?page=2&limit=20

2. File Paths

const folder = 'images';
const filename = 'photo.jpg';

const path = `./assets/${folder}/${filename}`;
console.log(path);
// ./assets/images/photo.jpg

3. CSS Class Names

const isActive = true;
const hasError = false;

const className = `btn ${isActive ? 'btn-active' : ''} ${hasError ? 'btn-error' : ''}`.trim();
console.log(className);
// btn btn-active

4. Logging and Debugging

const user = { id: 42, name: 'Alice' };
const action = 'login';

console.log(`[${new Date().toISOString()}] User ${user.id} (${user.name}) performed: ${action}`);
// [2026-02-07T08:00:00.000Z] User 42 (Alice) performed: login

5. Formatting Numbers

const price = 1234.56;
const quantity = 5;

console.log(`Price: $${price.toFixed(2)}`);
// Price: $1234.56

console.log(`Quantity: ${quantity.toString().padStart(3, '0')}`);
// Quantity: 005

const percent = 0.875;
console.log(`Progress: ${(percent * 100).toFixed(1)}%`);
// Progress: 87.5%

6. Building Lists

const items = ['apple', 'banana', 'orange'];

const message = `You have ${items.length} items: ${items.join(', ')}`;
console.log(message);
// You have 3 items: apple, banana, orange

const sentence = `Fruits: ${items.slice(0, -1).join(', ')} and ${items[items.length - 1]}`;
console.log(sentence);
// Fruits: apple, banana and orange

Tagged Templates (Advanced)

You can process template literals with a function (called a “tag”):

function highlight(strings, ...values) {
  return strings.reduce((result, str, i) => {
    return result + str + (values[i] ? `<mark>${values[i]}</mark>` : '');
  }, '');
}

const name = 'Alice';
const score = 95;

const result = highlight`Student ${name} scored ${score} points`;
console.log(result);
// Student <mark>Alice</mark> scored <mark>95</mark> points

Best Practices

DO:

// Use for string interpolation
const greeting = `Hello, ${name}!`;

// Use for multi-line strings
const html = `
  <div>
    <p>Content</p>
  </div>
`;

// Use for complex strings with multiple variables
const summary = `Order #${orderId}: ${quantity} items, total $${total}`;

// Use for readability
const url = `https://api.example.com/users/${userId}/posts/${postId}`;

DON’T:

// Don't use for simple strings without variables
const message = `Hello`;  // ❌ Use regular quotes
const message = 'Hello';  // ✅ Better

// Don't overcomplicate with too much logic
const complex = `Result: ${a > b ? (c > d ? x : y) : (e > f ? z : w)}`; // ❌ Hard to read
// Better: calculate first, then insert
const result = a > b ? (c > d ? x : y) : (e > f ? z : w);
const message = `Result: ${result}`;  // ✅ Clearer

// Don't forget to escape backticks when needed
const code = `Use ` for templates`;  // ❌ Syntax error
const code = `Use \` for templates`; // ✅ Correct

Template Literals vs Concatenation

Feature Template Literals Concatenation
Syntax `Hello ${name}` 'Hello ' + name
Readability ✅ High ⚠️ Low (many quotes)
Multi-line ✅ Native ❌ Needs \n
Expressions ${2 + 2} ❌ Must calculate separately
Performance ~Same ~Same
Escaping \` \' or \"

When to use which:

  • Template literals → any string with variables or multi-line
  • Single quotes → simple static strings
  • Double quotes → when string contains single quotes

Common Mistakes

1. Forgetting Dollar Sign

const name = 'Alice';

// ❌ Wrong - missing $
const greeting = `Hello, {name}!`;
console.log(greeting);  // Hello, {name}!

// ✅ Correct
const greeting = `Hello, ${name}!`;
console.log(greeting);  // Hello, Alice!

2. Using Quotes Instead of Backticks

const name = 'Alice';

// ❌ Wrong - using quotes
const greeting = "Hello, ${name}!";
console.log(greeting);  // Hello, ${name}!

// ✅ Correct - using backticks
const greeting = `Hello, ${name}!`;
console.log(greeting);  // Hello, Alice!

3. Unintended Whitespace

// ❌ Unintended leading/trailing whitespace
const html = `
  <div>Hello</div>
`;
console.log(html.length);  // Includes newlines and spaces

// ✅ Trim if needed
const html = `
  <div>Hello</div>
`.trim();

// ✅ Or write inline
const html = `<div>Hello</div>`;

Summary

Basic Syntax:

const result = `Text ${variable} more text`;

Key Features:

  • ✅ Variable interpolation: ${name}
  • ✅ Expression evaluation: ${2 + 2}
  • ✅ Multi-line strings (preserves newlines)
  • ✅ Function calls: ${getPrice()}
  • ✅ Nested templates possible

Use template literals when:

  • Inserting variables into strings
  • Creating multi-line strings
  • Building dynamic content (URLs, HTML, etc.)
  • Need readable string formatting

Quick Comparison:

// Concatenation (old)
const msg = 'Hello, ' + name + '! You have ' + count + ' items.';

// Template literal (modern)
const msg = `Hello, ${name}! You have ${count} items.`;