ES6 Template Literals

What Is String Interpolation?

ES6 is introducing many new features to the JavaScript spec. One of my favorite features is the template literal syntax which allows for sane string interpolation. For those of you who don’t know what string interpolation is, I offer you this quote from Wikipedia:

In computer programming, string interpolation or variable interpolation (also variable substitution or variable expansion) is the process of evaluating a string literal containing one or more placeholders, yielding a result in which the placeholders are replaced with their corresponding values.

Why exactly should you be excited about templates? Well, first, let me show you the way string interpolation is currently accomplished in JavaScript.

/*
* Let's say you want to tell a story, but you're not 100% sold on
* the characters you've created yet, so you want to store character
* information in an object and inject character properties like
* name, age, etc. into your writing. This way if you change them at
* a later time, you won't have to rewrite the story itself, you can
* just update the character info object and you're done!
*/
var characters =
{
protagonist: {
name: 'Tortoise',
speed: 'fast',
hobby: 'race'
  },
antagonist: {
name: 'Hare',
speed: 'fast',
hobby: 'race'
}
};
// Now we can write our story:
var story = "Once there was a " + characters.protagonist.name +
" who was very " + characters.protagonist.speed + " and loved nothing more than a good " + characters.protagonist.hobby + ".\n"

As you can plainly see, writing in this style gets old very quickly. Luckily ES6 is bringing along templates and proper string interpolation to solve this problem.

How Should We Interpolate?

The ES6 syntax for templates uses two tilde(`) characters to delimit a template. Inside this template you have access to some magical features. Let’s take a look at some code and dig a little deeper.

/*
* Using the same scenario, we will see how ES6 and templates will
* make it easier to write our story. We've decided to update our
* story because the tortoise doesn't feel very believable. We've
* also decided that we want to sharpen our ES6 skills while we're
* at it.
*/
var characters =
{
protagonist: {
name: 'Tortoise',
speed: 'slow',
hobby: 'walk'
},
antagonist: {
name: 'Hare',
speed: 'fast',
hobby: 'race'
}
};
// The ${expression} syntax allows you to inject expressions into
// your templates!
var story = `Once there was a ${characters.protagonist.name} 
who was very ${characters.protagonist.speed} and loved nothing more than a good ${characters.protagonist.hobby}.`

As you can see, ES6 template syntax makes it easy to substitute expressions into your templates. The template syntax is also much cleaner and easier to write. If you didn’t notice, new lines are interpreted and we also don’t have to concatenate a giant monster string anymore. Hurray ES6!