Template literals

Traditionally, in JavaScript, we concatenate strings using the + operator. However, if we want to concatenate multi-line strings, then we have to use the escape code \ to escape new lines, such as:

let a = '<div> \    <li>' + myVariable+ '</li> \</div>'

This can be very confusing when we have to write a string that contains a large amount of HTML. In this case, we can use ES6 template strings. Template strings are strings surrounded by backticks ` ` instead of single quotation marks ' '. By using this, we can create multi-line strings in an easier way:

let a = `<div>   <li> ${myVariable} </li></div>`

As you can see, we can create DOM elements in a similar way; we type them in HTML without worrying about spaces or multi-lines. ...

Get JavaScript by Example now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.