58

JS Monday 03 – The Handsome Template Literals

 5 years ago
source link: https://www.tuicool.com/articles/hit/6J7BVvm
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

What if we need to concatenate some strings?

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

RJJNFr6.png!webIfUR3aM.png!web

Such an ugly way to concatenate strings!

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

Av6rMbA.png!web67BZJri.png!web

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:

Nv67RjU.png!webMJrm2eb.png!web

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:

AfyQjuB.png!webj2Mziee.png!web

Or we can conditionally write parts of a string:

JZzeiaa.png!webnyeuqm3.png!web

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:

JJVZRjQ.png!webnyI32mZ.png!web

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

IJF3Ej6.png!web7v2QJ3Y.png!web

Wow! It will respect our indentation!

Tagged Templates

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

YFNJBji.png!webVn6rqe3.png!web

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:

YrimeiR.png!webbaiMBnu.png!web

But how does it work?

Let’s log our function arguments

6F3uYvf.png!web22QBJfV.png!web

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

ryUbaeR.png!webeAjQNrU.png!web

See you next week with a new episode of Js Monday!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK