Template Literals

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

let testString = `Hello World`

alert(testString)

 

Template literal 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}`

alert(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}`

alert(testString)

 

Template literals can span over several lines, as shown here (Run Example)

<!DOCTYPE html> 
<html> 
    <head>
        <title>Template Literal over several lines example</title>
        <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>`

            console.log(htmlString)
        </script>
    </head>
    <body> 
        <div>View the console output in browser's Web DevTools (F12)</div>
    </body> 
</html> 

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="file:///C|/Users/Derek/Documents/Notes/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:0color:whitebackground-color:white'>&nbsp;</a></div>