How to Use Template Literals in JavaScript | The School of Code

Settings

Appearance

Choose a typography theme that suits your style

Back to How-to Guides
JavaScript

How to Use Template Literals in JavaScript

Learn how to use template literals for string interpolation, multi-line strings, and tagged templates in JavaScript.

JavaScriptTemplate LiteralsES6Strings

Template literals (backtick strings) provide powerful string features including interpolation, multi-line support, and tagged templates.

Basic Syntax

// Regular strings
const regular = 'Hello World';

// Template literal
const template = `Hello World`;

String Interpolation

Embed expressions inside strings:

const name = 'Alice';
const age = 30;

// Old way (concatenation)
const old = 'My name is ' + name + ' and I am ' + age + ' years old.';

// Template literal
const modern = `My name is ${name} and I am ${age} years old.`;
console.log(modern); // My name is Alice and I am 30 years old.

Expressions in Templates

const a = 10;
const b = 20;

// Math expressions
console.log(`Sum: ${a + b}`);           // Sum: 30
console.log(`Product: ${a * b}`);       // Product: 200

// Function calls
console.log(`Uppercase: ${name.toUpperCase()}`);

// Ternary operators
const status = `User is ${age >= 18 ? 'adult' : 'minor'}`;

// Object properties
const user = { name: 'Bob', role: 'admin' };
console.log(`${user.name} is ${user.role}`);

Multi-line Strings

// Old way
const oldMulti = 'Line 1\n' +
                 'Line 2\n' +
                 'Line 3';

// Template literal - preserves line breaks
const multi = `Line 1
Line 2
Line 3`;

console.log(multi);
// Line 1
// Line 2
// Line 3

Nesting Templates

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

const list = `Items:
${items.map(item => `  - ${item}`).join('\n')}`;

console.log(list);
// Items:
//   - apple
//   - banana
//   - cherry

Tagged Templates

Process template literals with a function:

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

const name = 'Alice';
const action = 'logged in';
const result = highlight`User ${name} has ${action}`;
console.log(result);
// User <mark>Alice</mark> has <mark>logged in</mark>

Practical Examples

HTML Templates

const user = { name: 'Alice', email: 'alice@example.com' };

const html = `
<div class="user-card">
    <h2>${user.name}</h2>
    <p>${user.email}</p>
</div>
`;

SQL Queries (with caution)

// Note: Use parameterized queries in real applications!
const table = 'users';
const id = 5;
const query = `SELECT * FROM ${table} WHERE id = ${id}`;

URL Building

const baseUrl = 'https://api.example.com';
const endpoint = 'users';
const id = 123;

const url = `${baseUrl}/${endpoint}/${id}?format=json`;
console.log(url);
// https://api.example.com/users/123?format=json

Error Messages

function validateAge(age) {
    if (age < 0) {
        throw new Error(`Invalid age: ${age}. Age must be positive.`);
    }
    if (age > 150) {
        throw new Error(`Invalid age: ${age}. Age seems unrealistic.`);
    }
}

Raw Strings

Access the raw string without escape processing:

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

// Raw string
console.log(String.raw`Line1\nLine2`);
// Line1\nLine2 (literal backslash-n)

// Useful for regex patterns
const pattern = String.raw`\d+\.\d+`;
console.log(pattern); // \d+\.\d+

Escaping Backticks

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

// Or use regular strings
const alt = "Use `backticks` for template literals";

Summary

  • Use backticks (`) for template literals
  • ${expression} for interpolation
  • Supports multi-line strings naturally
  • Tagged templates for custom processing
  • String.raw for raw strings without escapes
  • Great for HTML, URLs, and dynamic messages