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 on screen 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 lines just the way the string was defined.

Variable Substitution

Another really interesting feature of declaring strings with ` is that they can now contain and 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

A small change to Javascript in ES6 but the convenience of multi-line strings and variable substitution is substantial.

results matching ""

    No results matching ""