WDD 131: Dynamic Web Fundamentals

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

Prepare

  1. Read Template Literals - MDN web docs
  2. The following parameters are the basic concepts of template literals:
    • Encase the literal in backticks (``).
    • Use string text to construct the literal.
    • Use JavaScript expressions inserted at a specific location within the literal using ${expression} notation.

Check Your Understanding

  1. Change this concatenated string into a template literal:
    let output = "Welcome to " + courseSubject + " " + courseNumber + "!
    Credits: " + courseCredits + "
    Length: " + courseLength;
    Check Your Understanding
    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;
    Check Your Understanding
    listItems += `<li>${temple}</li>`;