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
- Read Template Literals – MDN
- 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.
- Enclose the literal in backticks (
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
- 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}`; - Given the following script, finish the code snippet to produce a list of three temples based on the
templesarray: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>`;