An array of small circuits boards against a pale background

Adding content to the DOM often involves a series of concatenations to bring information into a static string, such as this example:

let name = "John",
time = "morning";
document.body.insertAdjacentHTML("afterbegin", 
"<p>Good "+ time +", " + name + "!</p>");

As you can see, the + concatenation and inserted variables make for a rather long and complex line of code that’s not terribly easy to read. This is just one of the aspects of JavaScript development that template literals were designed to address.

Ticks Not Quotes

The first thing that distinguishes template literals is that they use the backtick symbol rather than quotes. Within this, template expressions are preceded by a dollar sign and surrounded by curly braces. Our code turns to:

document.body.insertAdjacentHTML("afterbegin", 
`<p>Good ${time}, ${name}!</p>`);

The $() are known as string substitutions. The result, in our page, would be a complete paragraph:

<p>Good morning, John!</p>

In other words, it creates the same result as our earlier code, but in less space, while being significantly easier to read.

Template literals also have the advantage of stretching across multiple lines (with newline returns) without incurring any syntax errors:

document.body.insertAdjacentHTML("afterbegin", `<p>Good 
${time}, 
${name}!
</p>`);

This formatting also translates through to the DOM:

<p>Good 
morning,
John!</p>

Expressions, Not Just Strings

The code inside the curly braces in a template literal need not just be references to variables or constants; they can also contain expressions. To continue and expand the earlier example:

const today = new Date(),
currTime = today.getHours(),
name = "Bob",
age = 48;

function greeting() {
    if (currTime < 12) {
      return("morning")
    } else if (currTime < 18) {
      return("afternoon")
    } else {
      return("evening")
    }
}

document.body.insertAdjacentHTML("afterbegin", 
`<p>Good ${greeting()}, ${name}! You are ${age + 1} today!</p>`);

Once you become accustomed to the new syntax, these features make template literals extremely powerful.

Support

Template strings are a feature of ES6, but have excellent browser support: Chrome 41, Firefox 34, Opera 28 and Safari 9 and higher have support for the basic features. The only exception is Internet Explorer; if support there is important to you, I’d recommend using a transpiler like Babel.

Conclusion and Resources

There’s a lot more that you can do with template strings, which I will be covering in future articles. Wes Bos also has an excellent article on working with template strings, which I would recommend reading.

Photograph by Jeff Easter, used under a Creative Commons Generic Attribution 2.0 license

Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.