Template Literals

Template literals (also called "string literals") are strings that allow us to embed expressions. Template literals are enclosed by back-tick characters (``) instead of double or single quotes.

let testString = `Hello World`

console.log(testString)

 

Template literals support string interpolation, which means that they can contain embedded expressions. To embed an expression, place it inside a pair of {} brackets and preceed it with a $ character.

let name = "Mary"
let testString = `Hello ${name}`

console.log(testString)

 

A template literal expression can be any valid Javascript expression. For example:

let number = 3
let testString = `3 squared = ${number * number} and 2 + 5 = ${2 + 5}`

console.log(testString)

 

Template literals can span over several lines. This can be very useful if a string contains structured data. The example below shows a string that holds the HTML code to produce a table. By spanning the string over several lines, we can clearly see the structure of the <table>, <tr>, <th>, and <td> tags.

Example showing a template literal spanning over several lines (Run Example)

<!DOCTYPE html> 
<html> 
    <head>
        <title>Template Literal over several lines example</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">

        <script>
            let names = ["Anne", "Bob", "Cathy"]
            let htmlString = `<table>
                                  <tr><th>Forename</th></tr>
                                  <tr><td>${names[0]}</td></tr>
                                  <tr><td>${names[1]}</td></tr>
                                  <tr><td>${names[2]}</td></tr>
                              </table>`

            document.write(htmlString)
        </script>
    </head>

    <body> 
    </body> 
</html> 

Change the above code to use double-quotes " instead of back-ticks `. It will not run, because traditional strings (using single-quotes or double-quotes) cannot span over more than one line.

Adjust the code above to use a for-loop to process the three names in the array, as shown here.

Write code to display the two arrays below as formatted list. You must use a template literal, as shown here.

let people = ["Anne", "Bob", "Cathy", "David"]
let ages = [22, 24, 19, 20]

 
<div align="center"><a href="../versionC/index.html" title="DKIT Lecture notes homepage for Derek O&#39; Reilly, Dundalk Institute of Technology (DKIT), Dundalk, County Louth, Ireland. Copyright Derek O&#39; Reilly, DKIT." target="_parent" style='font-size:0;color:white;background-color:white'>&nbsp;</a></div>