#native_company# #native_desc#
#native_cta#

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. main.ts
'use strict';

let fname = "Asim";

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

Caught a mistake or want to contribute to the book? Edit this page on GitHub!



Advanced JavaScript

This unique course teaches you advanced JavaScript knowledge through a series of interview questions. Bring your JavaScript to the 2021's today.

Level up your JavaScript now!