Create your own
Lesson illustration

Template Literals: Interpolation and Multi-line Strings

Hello! Welcome to your next lesson in our front-end development course.

Introduction

In our last session, we successfully implemented visual feedback for form validation. We created functions like showError that constructed error messages, such as "Username is required.". While functional, building strings this way using the + operator can become clumsy, especially with multiple variables or line breaks.

Today, we'll learn a modern and much more elegant way to work with strings. This lesson addresses the learning outcome: Use template literals for string interpolation and multi-line strings.

Template literals are a feature introduced in ES6 (a modern version of JavaScript) that make creating complex strings incredibly simple and readable. As a designer, you'll appreciate how they clean up the code, making it more expressive and easier to maintain.

We will cover:

  • The limitations of traditional strings.
  • The basic syntax of template literals using backticks (`).
  • How to create multi-line strings without special characters.
  • How to embed variables and expressions directly into strings using interpolation.

1. The Problem with Traditional Strings

Before we dive into the solution, let's quickly see the problem we're trying to solve. When you need to combine variables with static text or create strings that span multiple lines, the old way in JavaScript can be awkward.

This short video clip clearly illustrates the challenges.

JavaScript Template Literals

This video from Programming with Mosh effectively demonstrates the pain points of concatenating strings with the + operator and creating multi-line strings with \n.

Watch from the beginning until 01:12. Notice how messy the code becomes when trying to add variables, quotes, and line breaks to a traditional string.

As you can see, the code doesn't visually match the output, and the need for + and \ characters adds "noise" that makes the string hard to read.


2. Introducing Template Literals

Template literals offer a cleaner syntax that solves these problems. They are defined using backticks (`) instead of single (' ') or double (" ") quotes.

Their two main superpowers are:

  1. Effortless Multi-line Strings: You can simply press Enter to create a new line. The string will preserve all the whitespace and line breaks.
  2. String Interpolation: You can embed variables or any valid JavaScript expression directly into the string using the ${...} syntax.

Let's watch the rest of that video to see how template literals work.

JavaScript Template Literals

Continuing with the same video, Mosh now introduces template literals and shows how they directly solve the problems he just highlighted.

Watch from 01:12 to 04:48. Pay close attention to: The use of backticks (`) to define the string. How a multi-line email message is formatted naturally. The ${name} syntax used to embed a variable directly into the string (this is called interpolation).


3. Template Literals vs. Regular Strings: A Side-by-Side Look

To solidify your understanding, let's review the key differences with a textual resource. This article from freeCodeCamp provides excellent side-by-side comparisons.

How to Use Template Literals in JavaScript

This article, 'How to Use Template Literals in JavaScript', provides clear code examples that contrast the old and new ways of handling strings.

Please read the sections titled 'Template Literals vs Regular Strings' and 'Generating HTML Markup'. Focus on the code examples for String Concatenation, Multi-line Strings, and Generating HTML. These directly relate to the kind of UI work you'll be doing.

The ability to generate HTML fragments is particularly powerful. As a designer moving into front-end, you can now write small, dynamic HTML components in a way that is both readable and directly mirrors the final structure.


4. Your Turn: Refactor and Create with Template Literals

Now it's time to apply what you've learned.

Part A: Refactoring Form Error Messages

In our last lesson, we wrote an errorMessage function for our validation logic. Let's refactor one of those messages using a template literal.

Original Code (from previous lesson):

const validationOptions = [
    // ... other options
    {
        attribute: 'minlength',
        isValid: input => input.value.length >= parseInt(input.minLength, 10),
        errorMessage: (input) => getLabelText(input) + ' must be at least ' + input.minLength + ' characters.',
    }
    // ... other options
];

Refactored with a Template Literal:

const validationOptions = [
    // ... other options
    {
        attribute: 'minlength',
        isValid: input => input.value.length >= parseInt(input.minLength, 10),
        errorMessage: (input) => `${getLabelText(input)} must be at least ${input.minLength} characters.`,
    }
    // ... other options
];

Notice how the refactored version is a single, unbroken string. The variables getLabelText(input) (which is a function call that returns a value) and input.minLength are seamlessly embedded. It's much easier to read and write.

Part B: Practice Exercise

Let's use template literals to generate a dynamic user profile card.

Your Goal:
Complete the createUserProfileCard function. It takes a user object as an argument and should return a multi-line string containing HTML. Use a template literal to construct this HTML, embedding the user's name, username, and bio into the appropriate tags.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Template Literals Practice</title>
    <style>
        body { font-family: sans-serif; background-color: #f0f2f5; display: flex; justify-content: center; align-items: center; height: 100vh; }
        .profile-card {
            background: #fff;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
            padding: 24px;
            width: 350px;
            text-align: center;
        }
        .profile-card h2 { margin: 0 0 4px; }
        .profile-card .username { color: #657786; margin-top: 0; margin-bottom: 16px; }
        .profile-card .bio { font-size: 0.95rem; line-height: 1.5; }
    </style>
</head>
<body>

    <div id="profile-container"></div>

    <script>
        const user = {
            name: 'Alex Doe',
            username: '@alexdoe_designs',
            bio: 'UI/UX Designer with a passion for creating intuitive and beautiful digital experiences. Lover of clean code and good coffee.'
        };

        /**
         * Creates an HTML string for a user profile card.
         * @param {object} user - The user object with name, username, and bio.
         * @returns {string} A multi-line HTML string.
         */
        function createUserProfileCard(user) {
            // --- YOUR CODE HERE ---
            // Use a template literal to create the HTML structure below.
            // Replace the placeholder text with values from the user object
            // using string interpolation.
            /*
            <div class="profile-card">
                <h2>USER_NAME</h2>
                <p class="username">USER_USERNAME</p>
                <p class="bio">USER_BIO</p>
            </div>
            */
           
            // Example of what the first line might look like:
            // return `<div class="profile-card">
            //            <h2>${user.name}</h2>
            //            ... and so on
            //        </div>`;
        }

        // --- Render the profile card to the page ---
        const profileContainer = document.querySelector('#profile-container');
        profileContainer.innerHTML = createUserProfileCard(user);

    </script>

</body>
</html>
Click here for the solution
function createUserProfileCard(user) {
    return `
        <div class="profile-card">
            <h2>${user.name}</h2>
            <p class="username">${user.username}</p>
            <p class="bio">${user.bio}</p>
        </div>
    `;
}

Conclusion

Great job! You've just learned a feature that you will use constantly in modern JavaScript development. It's a small change in syntax that leads to a big improvement in code quality.

Key Takeaways:

  • Template literals are defined with backticks (`).
  • They allow for multi-line strings without needing \n, making your code's formatting match the output.
  • They support string interpolation with the ${expression} syntax, allowing you to easily embed variables and expressions into strings.
  • This makes code for generating dynamic text, error messages, or HTML fragments much cleaner and more readable.

In our next lesson, we'll continue exploring modern JavaScript by learning about destructuring, another powerful feature that provides a concise way to extract values from objects and arrays.

Can't find a good explanation? Sign up and we'll make it for you

Sign up