CSE 121B: JavaScript Language

Template Literals (Template Strings)

Overview

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

"Template literals are literals delimited with backtick (`) characters, allowing for multi-line strings, string interpolation with embedded expressions, and special constructs called tagged templates". - MDN web docs

Prepare

The following parameters are the basic concepts of template literals:

  1. Read 📝Template Literals - MDN web docs

Check Your Understanding

  1. Change this concatenated string into a template literal:
    let output = "Welcome to " + courseSubject + " " + courseNumber + "!
    Credits: " + courseCredits + "
    Length: " + courseLength;
    Answer
    let output = `Welcome to ${courseSubject} ${courseNumber}!
    Credits: ${courseCredits}
    Length: ${courseLength}`;
  2. Given the following script, finish the code snippet to produce a list of three temples base on the temples array:
    let temples = ["Rome", "Salt Lake", "Nauvoo"];
    let listItems = "";
    for (const temple of temples) {
      listItems += `<li>__________</li>`;
    }
    document.querySelector("ul").innerHTML = listItems;
    Answer
    listItems += `<li>${temple}</li>`;