Copyright Derek O'Reilly, Dundalk Institute of Technology (DkIT), Dundalk, Co. Louth, Ireland.
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]
Copyright Derek O' Reilly, Dundalk Institute of Technology (DkIT), Dundalk, Co. Louth, Ireland.