Software Development | Template Literals

Template Literals (Template Strings)

Overview

JavaScript template literals are string literals that allow embedded expressions. They support multi-line strings and string interpolation. They are sometimes informally called "template strings."

"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
  2. The basic rules of template literals:
    • Enclose the literal in backticks (`).
    • Write the string text directly inside the backticks.
    • Insert JavaScript expressions at any location using ${expression} notation.

This example uses both interpolation and a multi-line string. Any expression can go inside ${}, including calculations and function calls.

const item = "notebook";
const price = 4.5;
const quantity = 3;

const message = `You ordered ${quantity} ${item}s.
Total: ${(price * quantity).toFixed(2)} USD`;

console.log(message);
// You ordered 3 notebooks.
// Total: 13.50 USD

Check Your Understanding

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