What are Template Strings in ES6?

Template strings or template literals is a new kind of string literal. Instead of double quotes and single quotes, we use blackticks to enclose string.

var str = `apple`;

console.log(typeof( str ));

// string

Interpolate expression

let name = 'Luffy';

let title = 'King of Pirates';

console.log(name +' is '+ title );

// Luffy is King of Pirates

Here we are concatenating strings with variables with plus operator. This way of creating longer strings can be error prone because we have to worry about space, plus operator and single quotes(or double quotes).

So let’s rewrite it using template literals.

let name = 'Luffy';

let title = 'King of Pirates';

console.log(` ${name} is ${title} `);

// Luffy is King of Pirates

With template literals, we put variables inside dollar sign with curly braces ( ${   } ). This will output values stored in variables as string.

Note that inside ${  } we can inject not just variables but any valid javascript expression such as function call.

This feature of template literals enable us to write dynamic strings with variables or any valid expression.

`Smallest number ${Math.min(34, 44, 12, 22)}`;

// 12

`the product of 2 and 5 is ${ 2 *5 }`;

// 10

Multi-line strings

You might want to break long strings to separate line for better readability but with single quote(or double quote) writing multi-line strings is quite cumbersome.

'Luffy\n'+

'is\n'+

'King of Pirates'

One of the helpful feature of template literals is that it allows to split string into multiple lines easily.

`

Luffy

is

King of Pirates

`