Template Literals in Javascript

Blossom
2 min readJun 13, 2020

--

Template literals is a feature that came with the ECMA version 2015, es6.

Es6 Template literals

Template literals is a better way of writing strings in javascript. Template literals are enclosed in double backticks (``, this can be found to the of 1 on the keyboard). Template literals also allow expressions to be written easily with strings.

Before the template literals, we would write strings like this:

console.log(“Love For All, Hatred For None ”)

Es6 Template literals: console.log(`Love For All, Hatred For None`)

No much difference at the moment you might think, but I will be highlighting three major ways where template literals come in handy over the regular string concatenation.

Multi-line Strings

multi-line string image

Using normal strings, we would have to do the following to get a new line:

console.log('To live is to die\n' +
'To die is to live');
// To live is to die
// To die is to live

\n this creates a new line and can get quite complicated when we have to write a really long message that requires lots of newlines.

In the Es6, we do this instead:

console.log(`To live is to die
To die is to live`);
// To live is to die
// To die is to live

Notice anything different?

No. Not the backtick. Look again.

There was no newline \n, yet if you console log the above, a new line will appear. With backticks, you can just use your enter key to create a new line and javascript will recognize it as a newline. You can even use double and single quote marks (‘ “) in the template literals without the \ symbol would normally use.

Get it yet?

Expression Interpolation

In order to use expressions within normal strings, we would write it like this:

let a = 5;
let b = 10;
console.log('Fifteen is ' + (a + b) )
// "Fifteen is 15

With es6, it is as simple as:

let a = 5;
let b = 10;
console.log('Fifteen is ' ${a + b} )

Template literals are not just limited to the above illustrations, a good place to continue is with the men documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

Happy coding.

--

--