Template Literals (Template Strings)
Overview
JavaScript template literals are string literals allowing embedded expressions and are a better choice than traditional string concatenation. You can use multi-line strings and string interpolation features with template literals. They were called "template strings" in prior editions of the ES2015 specification.
Prepare
Template literals are enclosed by the backtick (`) (grave accent) character instead of double or
single quotes. Template literals can contain placeholders. These are indicated by the dollar sign and curly braces
(${expression}). The expressions in the placeholders and the text between the backticks get passed to
a function.
For example, given that let name = "World", you can create a greeting message like this:
let message = `Hello, ${name}!`;
This will set message to "Hello, World!".
The following parameters are the basic concepts of using 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 given that the variables
courseSubject,courseNumber, andcourseCredits, are defined.let output = "Welcome to " + courseSubject + " " + courseNumber + "!<br>Credits: " + courseCreditsCheck Your Understanding
let output = `Welcome to ${courseSubject} ${courseNumber}!<br>Credits: ${courseCredits}`; - Given the following script, finish the code snippet to produce an unordered list of three temples based on the
templesarray using template literals.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>`;