Template Strings

Multi-Line Strings

With ES5 and ES6 we can specify a string with either the ' or " characters.

let single = "hello world";

But in ES5 if we wanted to make that string span multiple lines it quickly becomes a pain.

let single = 'hello ' +
    'world ' +
    'my ' +
    'name ' +
    'is ' +
    'asim';

If we wanted each line in the string to contain new line characters, matching how it was written, we had to remember to add \n to the end of each string.

let single = 'hello\n' +
    'world\n' +
    'my\n' +
    'name\n' +
    'is\n' +
    'asim\n';

In ES6 we have another way of defining strings, using the back-tick character `

let multi = `
hello
world
my
name
is
asim`;
console.log(multi);

The above prints out:

hello
world
my
name
is
asim

With ` strings can now span multiple lines and they are also formatted with new line characters.

Variable Substitution

Another really interesting feature of declaring strings with ` is that they can now expand variables using the ${variable_name} syntax, like so:

let name = "asim";

let multi = `
hello
world
my
name
is
${name}
`;
console.log(multi);

prints out:

hello
world
my
name
is
asim

Summary

Template strings are a small change to JavaScript in ES6 but the convenience of multi-line strings and variable substitution is substantial.

Listing

Listing 1. script.js
'use strict';

let name = "Asim";

let multi = `hello
world
my
name
is
${name}`;
console.log(multi);

Learn Angular 5 For FREE

I've released my 700 page Kick Starter funded Angular 5 book for FREE