Writing cleaner code with JavaScript 2015 template strings

JavaScript 2015 is the next version of JavaScript. Its official name is ECMAScript 2015 and sometimes it's called ES6.

This article discusses how you can use JS 2015 today and use the template strings feature to write cleaner and more readable code.

If you've used Babel before, skip right to reading the "Multiline strings and template variables" section.

Using JS 2015 today with Babel

Currently, no browser has full support for JavaScript 2015. Because of that, you need a converter that translates JS 2015 code into traditional JavaScript. In your HTML, you then include the generated file that contains traditional JS code, rather than including the JS 2015 code you wrote.

One tool to convert JS 2015 code into code that works today is Babel. There are some JS 2015 features that Babel doesn't support. Most of them are related to the Object APIs rather than the language itself. To be safe, stick to the features described on the Babel.js website.

You can try Babel online or run it on your computer. For example, there are Grunt and Gulp plugins available on the Babel website.

The easiest way to get started is to install the Babel command line tool. Run this command to install it using npm.

npm install -g babel

(Usually needs to run as administrator, add sudo before npm on Mac/Linux.)

Example: Converting a JavaScript 2015 file

Here's some example JavaScript 2015 code:

var greeting = `Hello`;

Note the use of backticks instead of quote signs, which indicates a special type of string in JS 2015. This code will run fine in Chrome or Firefox, but older browsers will show an error message:

SyntaxError: Invalid character: '`'

You need to run Babel to convert the code to a JavaScript version that today's browsers support.

If you call your JavaScript file js2015.js you can run this command to translate the JS 2015 code to traditional JS.

babel js2015.js --out-file traditional.js

Now traditional.js contains this code, which is supported by all browsers:

"use strict";

var greeting = "Hello";

You can add the watch flag to the Babel command to automatically update the traditional.js file every time you make a change to the JS 2015 code.

babel js2015.js --out-file traditional.js --watch

Now let's look at template strings, and why they are a great addition to the language.

Multiline strings and template variables

The strings above, with the backtick, are called template strings. They have two properties that are useful:

  1. They can span multiple lines
  2. They can contain placeholders that are replaced by variable values

Multiple lines

Multi-line strings are convenient, because you don't need to write the lines separately and then join them together with the new line character \n.

For example, you can write...

console.log(`Hi,
How are you?`);

... instead of concatenating two separate strings:

console.log("Hi,\n"
+ "How are you?");

Of course, in this example, you could just use "Hi,\nHow are you" instead of joining the two strings together. But this quickly gets messy when your string is longer than two lines.

Variable interpolation

Template strings also provide a string interpolation syntax that allows you to avoid string concatenation ("Hi " + name + ...).

Instead, you can reference the variables directly from inside the string:

var name = "Terry";
console.log(`Hello ${name}!`);

The ${name} syntax also supports more complex expressions inside the placeholder:

var a = 4;
var b = 8;
console.log(`${a} + ${b} = ${a + b}`);
// 4 + 8 = 12;

Another example of a more complex placeholder expression would be accessing object properties, for example ${Math.PI}.

Using template strings for... templates

Here's an example that combines the two features introduced above to compose an automated email:

var name = "Brendan";
var signupUrl = "http://example.com";
var email = `Hi ${name},

Please sign up for the event here: ${signupUrl}

Thanks,
The Event Team`;

And this is the value of email after running the code above:

Hi Brendan,

Please sign up for the event here: http://example.com

Thanks,
The Event Team

You can see why they're called template strings! They make it easy and clean to write templates in JavaScript.

Some example use cases for template strings are generating emails, generating HTML code or just putting multi-line content into a textarea element.

Get an email with a new articles once a week.