WDD Topics

Template Literals (Template Strings)

Overview

JavaScript template literals are string literals allowing embedded expressions and are a better choice than traditional string concatenation. You can use multi-line strings and string interpolation features with template literals. They were called "template strings" in prior editions of the ES2015 specification.

Prepare

Template literals are enclosed by the backtick (`) (grave accent) character instead of double or single quotes. Template literals can contain placeholders. These are indicated by the dollar sign and curly braces (${expression}). The expressions in the placeholders and the text between the backticks get passed to a function.

For example, given that let name = "World", you can create a greeting message like this:

let message = `Hello, ${name}!`;

This will set message to "Hello, World!".

The following parameters are the basic concepts of using template literals:

Check Your Understanding

  1. Change this concatenated string into a template literal given that the variables courseSubject, courseNumber, and courseCredits, are defined.
    let output = "Welcome to " + courseSubject + " " + courseNumber + "!<br>Credits: " + courseCredits
    Check Your Understanding
    let output = `Welcome to ${courseSubject} ${courseNumber}!<br>Credits: ${courseCredits}`;
  2. Given the following script, finish the code snippet to produce an unordered list of three temples based on the temples array using template literals.
    let temples = ["Rome", "Salt Lake", "Nauvoo"];
    let listItems = "";
    for (const temple of temples) {
      listItems += `<li>__________</li>`;
    }
    document.querySelector("ul").innerHTML = listItems;
    Check Your Understanding
    listItems += `<li>${temple}</li>`;