Switching to ES6 (Part 2: String Interpolation and Template Literals)

The Swiss Army Knife of strings.

Sunny Beatteay
Predict
4 min readJul 6, 2017

--

(If you missed the first part, you can find it here)

String interpolation is definitely my favorite new feature in ES6. Having a Ruby background, I find nothing more simple than:

adj = 'simple'
"A #{adj} interpolated string."

The lack of elegant string interpolation was the first thing I noticed about ES5.

“String concatenation? What sort of Dark Ages malarky is this? Even PHP has string interpolation! C’mon! Who’s even driving this thing?” I decried.

But it’s finally arrived! Gone are the days of:

var expletive = '#$%@&$%^#';"needing to concat every " + expletive + " string";

Say hello to:

let size = 'giant';`What a ${size} leap forward!.`;

String Interpolation using Template Literals

The syntax for template literals will be a bit strange for anyone who is a JavaScript purist. First, you need to surround the string you want to interpolate with backticks, which you can find at the top left of your keyboard under the esc key (American keyboards).

"wrong"
'wrong'
`correct`

Second, you need to surround the JavaScript code that you want interpolated with these brackets: ${}. And yes, the $ is required.

`{wrong}`
`$wrong`
`${correct}`

Here’s what an example code snippet using ES6 template literals would look like:

const names = ['Curly', 'Moe', 'Larry'];`The Three Stooges were ${names.slice(0, 2).join(', ')} and ${names[2]}.`// "The Three Stooges were Curly, Moe and Larry."

Template Literals: The Swiss Army Knife of strings

While string interpolation is handy, template literals provide us with many more features.

Escaping Nested Quotes

One of the things I love about template strings is that they are declarative. You just need to write the string how you want it to look and the JavaScript interpreter will take care of the rest.

Take nested quotation marks for instance. Typically, if you wanted to create nested quotes, you would have to escape the quotation characters so the interpreter wouldn’t accidentally end the string early or switch between double and single quotes.

// ES5"This is a \"nested string\"."// or'This is also a \'nested string\'.'// or"This is another 'nested string'."

Template literals remove that headache.

// ES6`This is a "nested string".`// "This is a \"nested string\"."

Multi-line Strings

Multi-line strings in ES5 are a pain. Not only do you need to include a new line character, \n, you need concatenate the strings across the lines as well.

Taken from MDN:

// ES5console.log('string text line 1\n' +
'string text line 2');
// "string text line 1
// string text line 2"

Template strings do all the work of structuring the string so you just need to write it how you want it to look:

// ES6console.log(`string text line 1
string text line 2`);
// "string text line 1
// string text line 2"

Tagging

Tag functions are a great way to keep your code DRY. If you find yourself needing to interpolate strings over and over in the same way, you can create a tag function to do it for you.

The first argument passed into a tag function is the string you want to convert. The rest of the arguments correlate with any ${} expressions you have in your string. The function will parse those expressions out and use them.

// Tag Functionvar person = 'Mike';
var age = 28;

function myTag(strings, personExp, ageExp) {
// The string is split using the expressions as delimiters.
// the 'strings' argument is returned as an array
// of the text snippets which you can access.
var str0 = strings[0]; // "that "
var str1 = strings[1]; // " is a "

var ageStr;
if (ageExp > 99){
ageStr = 'centenarian';
} else {
ageStr = 'youngster';
}

return str0 + personExp + str1 + ageStr;

}

var output = myTag`that ${ person } is a ${ age }`;

console.log(output);
// that Mike is a youngster

When to use Template Literals

When is the best time to use template literals?

Quite honestly, you could completely replace single quotes and double quotes for backticks. That may be a controversial opinion as I have only seen a couple people advocate that position, but it’s possible. Backticks do remove a lot of headache.

The only places that template literals will get you into trouble is with ESLint, JSON and 'use strict'. We still need to use quotes for those.

Many people would say that the accepted or “sensible” approach is to use backticks for interpolation or multi-line strings and single quotes for everything else, but there’s no requirement enforcing that. Ultimately, it will come down to personal preference.

For me, I’ll stick with the ‘ticks.

While browser support for ES6 is very high, it is still not 100%. If you are worried about backwards compatibility for your application, check out this article on how to easily convert ES6 into ES5.

--

--