Course contentsShow
← JavaScript
Lesson 151 of 2,7235. StringsFree lesson

Nesting Template Literals

Combine template literals within expressions for complex string construction.

Nesting Template Literals

You'll learn how to place one template literal inside another to build complex, dynamic strings layer by layer.

The Core Idea

Just as you can nest parentheses in math or put boxes inside boxes, you can embed an entire template literal within the ${} expression slot of another template literal. This is powerful when you need conditional or multi-part string construction—building a string whose own parts are dynamically generated strings.

Think of it like Russian nesting dolls: the outer doll contains an inner doll, and each can have its own decorations and structure.

How It Works

When JavaScript evaluates ${}, it expects an expression. Since a template literal is an expression, you can write:

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

const greeting = `Hello, ${`Name: ${name}, Age: ${age}`}!`;
console.log(greeting);
// "Hello, Name: Alice, Age: 30!"

The inner template literal `Name: ${name}, Age: ${age}` is evaluated first, producing "Name: Alice, Age: 30", which then gets inserted into the outer template literal.

Practical Use: Conditional Parts

const isOnline = true;
const username = 'Bob';

const status = `User ${username} is ${`currently ${isOnline ? 'online' : 'offline'}`}`;
console.log(status);
// "User Bob is currently online"

Here the nested template literal builds the status phrase conditionally before being inserted into the main message.

Key Takeaway: You can nest template literals inside ${} placeholders to dynamically construct complex strings from smaller, evaluated string pieces—each layer builds upon the inner results.