What if we need to concatenate some strings?

ES5 forces us to approach the problem in the following way:

Such an ugly way to concatenate strings!

Thankfully, with ES6 JavaScript introduces Template Literals, which will help us to concatenate strings as follows:

The greatest part of template literals, is that you can write any kind of JavaScript expression inside a string.

Let me explain that with the following code:

We just made some math inside a string!

Why should we care about writing some expressions inside a string?

Because sometimes it can make things easier. We can call functions, doing maths and other kind of stuff without writing extra boilerplate code.

We could call (as an example) a method which will calculate a trinagle area:

Or we can conditionally write parts of a string:

And please note another great thing: in the above example, we were able to use both double and single quotes characters without escaping them!

Multiline strings with ease

Another great thing about template literals, is that we are able to write multiline strings inside of them:

You will also be able to format your text as you prefer, try to run the following code in a browser:

Wow! It will respect our indentation!

Tagged Templates

A tagged template is a function which uses template literals to get its arguments:

What? Did we call a function without brackets?

Yeah we did! But that’s a silly example, let’s write down a function which is actually useful:

But how does it work?

Let’s log our function arguments

So we can assume that tagged template, allowed us to avoid the following code, making things easier: