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
- Read Template Literals - MDN web docs
- 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
- 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}`; - 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>`;