Hello again! In our last lesson, we mastered the spread operator (...), a crucial tool for creating copies of arrays and objects without modifying the original data. This principle of immutability is fundamental to how React manages data, and you'll be using spread syntax constantly.
We're now moving on to another modern JavaScript feature that will significantly clean up your code: template literals. Today's lesson is all about learning how to use them to construct strings that contain variables and even logic, a task that is often clumsy with traditional methods. For anyone building user interfaces, dynamically creating text is a daily activity, and template literals make this process elegant and readable.
The Problem: Clunky String Concatenation
Before we jump into the new syntax, let's look at why it's needed. Historically, if you wanted to combine strings with variables, you had to use the + operator for concatenation.
Consider this simple example:
const name = "Alex";
const itemCount = 3;
// Traditional concatenation
const message = "Hello " + name + ", you have " + itemCount + " items in your cart.";
console.log(message);
// Output: Hello Alex, you have 3 items in your cart.
This works, but it's not very readable. You have to juggle single or double quotes, manually add spaces, and sprinkle + operators everywhere. If you need a multi-line string or a calculation, it gets even messier:
const price = 9.99;
const tax = 0.07;
// A more complex concatenation
const invoiceDetails = "Invoice for " + name + ".\n" +
"Subtotal: $" + (itemCount * price).toFixed(2) + "\n" +
"Thank you for your order!";
console.log(invoiceDetails);
// Output:
// Invoice for Alex.
// Subtotal: $29.97
// Thank you for your order!
Notice the awkward \n for new lines and the parentheses needed for the calculation. This style of code is hard to write and even harder to read. The image below contrasts this older style with the modern approach we're about to learn.

The Solution: Template Literals
Template literals (also called template strings) offer a much better way. They are defined using backticks (`), the key usually to the left of the number 1 on your keyboard.
Their most powerful feature is the ability to embed expressions directly inside the string. This is called interpolation.
Let's look at the basic structure.

As the diagram shows, you wrap any JavaScript variable or expression in ${...}, and its resulting value is automatically placed into the string.
Here is our first example rewritten with a template literal:
const name = "Alex";
const itemCount = 3;
// Using a template literal
const message = `Hello ${name}, you have ${itemCount} items in your cart.`;
console.log(message);
// Output: Hello Alex, you have 3 items in your cart.
Already, this is much cleaner and more intuitive to read.
Exploring the Features of Template Literals
Template literals come with several benefits that solve the problems of traditional string handling. The resource from W3Schools provides a great overview of these core features.
This W3Schools page clearly introduces the syntax and main advantages of template literals.
As you read, focus on the following key sections and their examples: Back-Tics Syntax: The fundamental change from "" or '' to ``. Quotes Inside Strings: Notice how you can now use quotes without needing to escape them with a backslash. Multiline Strings: See how creating multiline text becomes natural—the line breaks in your code are preserved in the string. Interpolation: This is the most important part. Study the Variable Substitutions example to understand how variables are embedded. Expression Substitution: Go one step further and see how you can embed not just variables, but full expressions, like mathematical calculations.
The Power of Embedded Expressions
As you just read, the true power of template literals lies in embedding expressions. Any JavaScript code that produces a value can be placed inside ${...}. This opens up a world of possibilities for creating dynamic content cleanly.
Let's see this in action with a short video from Programming with Mosh, who provides some excellent and concise examples.
This video demonstrates how template literals simplify string formatting and allow for dynamic content.
First, watch the initial segment on multi-line formatting, where he contrasts the old, messy way with the clean template literal approach. Then, watch the key part on embedding expressions. Pay close attention to how he inserts a variable, performs a calculation, and even mentions calling a function—all from within the string.
Let's solidify this with a few more examples of what you can do inside ${...}:
1. Arithmetic and Method Calls
You can perform calculations and call object methods directly.
const item = {
name: "Laptop",
price: 1200,
quantity: 2
};
const summary = `Order: ${item.quantity} x ${item.name.toUpperCase()}
Total Cost: $${item.price * item.quantity}`;
console.log(summary);
// Output:
// Order: 2 x LAPTOP
// Total Cost: $2400
2. Conditional Logic with Ternary Operators
You can even use conditional (ternary) operators to change the output based on a condition.
const user = {
name: "Sam",
isLoggedIn: true
};
const greeting = `Welcome, ${user.isLoggedIn ? user.name : "Guest"}!`;
console.log(greeting);
// Output: Welcome, Sam!
A Practical Use Case: Generating HTML
One of the most common uses for template literals, especially as you move towards React, is generating blocks of HTML. Because template literals handle multi-line strings so well, you can write out an HTML structure in a readable way and inject data exactly where you need it.
const blogPost = {
title: "Why JavaScript is Awesome",
author: "Chris",
tags: ["code", "webdev", "es6"]
};
const postMarkup = `
<article class="post">
<h2>${blogPost.title}</h2>
<p>By ${blogPost.author}</p>
<ul>
<li>${blogPost.tags[0]}</li>
<li>${blogPost.tags[1]}</li>
<li>${blogPost.tags[2]}</li>
</ul>
</article>
`;
console.log(postMarkup);
This pattern of combining markup and JavaScript logic is a conceptual stepping stone to understanding JSX, the syntax you will use in React. The following resource shows a few more excellent, practical examples, including this HTML use case.
JavaScript Template Literals: Syntax, Usage, and Examples
This article from Mimo provides concise, practical examples of template literals in common scenarios.
Focus on these two sections: This part gives a direct side-by-side comparison that reinforces the readability benefit. This section shows a clear example of generating an HTML snippet, a very common task in web development.
Key Takeaways
You've now learned a cleaner, more powerful way to work with strings in JavaScript. This skill will make your code more professional and easier to maintain.
- Template literals are defined with backticks (
`) instead of quotes. - They naturally support multi-line strings without needing special characters like
\n. - The
${...}syntax, known as interpolation, allows you to embed any JavaScript variable or expression directly into the string. - This makes creating dynamic text—from simple greetings to complex HTML structures—far more readable and less error-prone than traditional string concatenation.
Next Steps
This lesson completes our tour of the essential modern JavaScript syntax features that are prerequisites for React. You've learned about let/const, arrow functions, array methods, destructuring, the spread operator, and now template literals.
In our final lesson for this module, we will cover a crucial topic for building larger applications: how to organize code into reusable modules using import and export statements. This will set the stage for us to finally leave the world of isolated scripts and start building structured projects.