Exploring ECMAScript 2015 (ES6): Template Literals

Template literals—formerly referred to as template strings—are a flexible way to handle strings in JavaScript. The new syntax uses backticks ` instead of single or double quotes. As a result, one quick bonus of the syntax is that you can include single or double quotation marks in your string without having to escape the characters.

const simpleStr = `This is a string.`;  
const strWithQuotes = `"And she said, 'This new string syntax is useful.'"`;  

Another feature of template literals is string interpolation. String interpolation is evaluating a string literal with placeholders, and filling in those placeholders with a template substitution. This means you can plug your variables right into a string without concatenating multiple strings.

var person = {  
  firstName: 'John',
  lastName: 'Doe'
}
var event = 'Muppetpalooza';  
var day = 'Saturday';

// ES2015
const greeting = `Welcome to ${event} on this fine ${day}, ${person.firstName} ${person.lastName}.`;

// ES5
var greeting2 = 'Welcome to ' + event + ' on this fine ' +  
                day + ', ' + person.firstName + ' ' + 
                person.lastName + '.';

Unlike other strings literals in JavaScript, template literals can span multiple lines. This again saves us having to rely on string concatenation.

// ES2015
const lyrics = `Welcome back my friends to the show that never ends  
We're so glad you could attend  
Come inside! Come inside!`;

// ES5
var lyrics = 'Welcome back my friends to the show that never ends\n' +  
'We\'re so glad you could attend\n' +  
'Come inside! Come inside!';  

Template literals also allow for custom interpolation through the use of tagged templates, but this is a more in depth topic outside the limited scope of this post. I may write a more detailed post in the future exploring custom interpolation.

Template literals add a lot of flexibility to JavaScript strings. String interpolation is something that has been available in many other languages for a long time, and now we can take advantage of them in JavaScript. Unescaped quotations marks, string interpolation, and multi-line strings are a few of the new conveniences template literals bring to JavaScript with EcmaScript 2015.

Further Reading

Tyler Walters

Written by Tyler Walters

Tyler Walters is a software engineer in Phoenix, Arizona. He is married to a beautiful woman and has three incredible daughters. He is interested in game development, writing, beer, and hot wings.