Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 56

Template Literals: Multi-line and Interpolated Strings

This lesson is built with resources from youtube.com, education.launchcode.org and 1 more site.

Hello! Welcome to a new module focused on Modern JavaScript, also known as ES6 and beyond. In the previous module, you built a strong foundation in working with arrays using powerful methods like map, filter, and reduce. Now, we're going to explore features of the language that make your code more expressive, easier to read, and more powerful.

Today, we'll start with a feature that will fundamentally change how you work with strings. We'll be looking at template literals, which provide a modern, elegant way to create strings, especially ones that include variables or span multiple lines.

Your goal for this lesson is to be able to define multi-line and interpolated strings using template literals. This is a crucial skill for building modern applications, especially when creating dynamic user interfaces in frameworks like Next.js.

The Problem: The Old Way of Combining Strings

Before ES6, if you wanted to combine strings and variables, you had to use string concatenation with the + operator. While functional, it can quickly become messy and hard to read.

Template Literal vs String Concatenation
This image perfectly illustrates the difference between old-school string concatenation and modern template literals. The "Senior" approach is what you will master today.

The "Junior" approach in the image uses concatenation. Imagine trying to build a more complex sentence:

const item = "Coffee";
const price = 5;
const quantity = 2;

// The old, clumsy way
const message = "You ordered " + quantity + " " + item + "s. Your total is $" + (price * quantity) + ".";

console.log(message); // Output: You ordered 2 Coffees. Your total is $10.

Notice the issues:

  • It's hard to read with all the + signs.
  • You have to manually add spaces inside the quotes (" "). Forgetting one is a common bug.
  • Combining strings and calculations like (price * quantity) feels awkward.

The Solution: Template Literals

Template literals solve all these problems. They were introduced in ES6 to make working with strings more intuitive. There are two key features to learn:

  1. Syntax: They use backticks (`) instead of single (') or double (") quotes. The backtick key is usually located above the Tab key on most keyboards.
  2. Interpolation: They allow you to embed variables and expressions directly into the string using the ${...} syntax. This is called string interpolation.

Let's see this in action.

Working with Strings in JavaScript - Concatenation & Template Literals Explained

To understand the basics of template literals and why they're so powerful, let's watch this video. It clearly explains the syntax and the concept of embedding 'expressions' inside a string.

Watch from 09:41 to 15:00. Pay attention to the backtick () syntax and how the ${...}` placeholder is used to insert variables and even perform calculations directly inside the string. Notice how much cleaner this is compared to the old concatenation method.

As the video demonstrated, an expression is any piece of code that results in a value. This means you can put more than just a variable name inside ${...}. You can do math, call functions, or use other operators.

Here's our previous example, rewritten with a template literal:

const item = "Coffee";
const price = 5;
const quantity = 2;

// The new, clean way
const message = `You ordered ${quantity} ${item}s. Your total is $${price * quantity}.`;

console.log(message); // Output: You ordered 2 Coffees. Your total is $10.

This is much more readable and maintainable. The string looks like the final output, with placeholders for the dynamic parts.


Handling Multi-line Strings with Ease

Another major advantage of template literals is how they handle strings that span multiple lines. With regular strings, you had to use the newline character (\n) and concatenation, which was cumbersome.

#14 Template Literals | JavaScript Full Tutorial

Another huge benefit of template literals is how they handle strings that span multiple lines. This video shows a great comparison.

Watch from 03:34 to 04:40. See how you can just press 'Enter' inside a template literal to create a new line, compared to the old way of using the \n character.

As you just saw, with template literals, what you see is what you get. Any line breaks you type inside the backticks are preserved in the final string.

// The old way
const oldPoem = "The mind chases happiness.\n" +
                "The heart creates happiness.\n" +
                "The soul is happiness.";

// The template literal way
const newPoem = `The mind chases happiness.
The heart creates happiness.
The soul is happiness.`;

console.log(oldPoem);
console.log(newPoem); // Both produce the exact same multi-line output
Test your understanding!

You have two variables, firstName and lastName. Create a greeting variable that produces the string "Hello, [firstName] [lastName]! Welcome.".

For example, if firstName is "Jane" and lastName is "Doe", the greeting should be "Hello, Jane Doe! Welcome.".

Use a template literal to achieve this.

Show answer
const firstName = "Jane";
const lastName = "Doe";

const greeting = `Hello, ${firstName} ${lastName}! Welcome.`;

console.log(greeting); // Output: Hello, Jane Doe! Welcome.

Explanation: We use backticks to start and end the string. The variables firstName and lastName are embedded directly into the string using the ${...} syntax, with a space between them to format the full name correctly.


Practical Use Case: Building HTML

This ability to create clean, multi-line, interpolated strings is incredibly important for your goal of learning Next.js. In modern web development, you often generate HTML dynamically based on JavaScript data. Template literals are perfect for this.

How to Use Template Literals in JavaScript

Now, let's see a practical use case that you'll encounter frequently when you start building applications with frameworks like Next.js. This article shows how template literals are perfect for generating dynamic HTML.

Read the section titled 'Some Practical Use Cases of Template Literals', focusing on the first example under 'Generating HTML Markup'. This demonstrates how you can build a block of HTML using data from a JavaScript object.

The example from the article is a pattern you will see over and over again:

const user = {
  name: "Marie",
  age: 25,
};

// A multi-line string that creates an HTML block
const userProfile = `
  <div>
    <h2>Name: ${user.name}</h2>
    <p>Age: ${user.age}</p>
  </div>
`;

This userProfile string can then be inserted directly into a webpage. This is the foundation of how components in frameworks like React and Next.js render data.


Conclusion

You've now learned a modern, powerful, and much cleaner way to work with strings in JavaScript. This will make your code more readable and less prone to errors.

Key Takeaways:

  • Template Literals are defined with backticks (`).
  • You can embed variables and expressions directly into the string using string interpolation with the ${...} syntax.
  • They naturally support multi-line strings without needing special characters like \n.
  • They are the preferred method for building strings in modern JavaScript, especially for creating dynamic content like HTML.
JavaScript Template Literals Explained
This image provides a great visual summary of the features and benefits of template literals you've learned today.

Next Up

Template literals give us a new syntax to compose strings from variables. In the next lesson, we'll learn about a complementary feature called destructuring. It provides a new syntax to do the opposite: efficiently extract values from objects and arrays into variables. This will be another big step in writing clean and modern JavaScript.