Do you use Template Literals in JavaScript?

String manipulations and formatting is one of the tedious tasks in many programming languages and it is true in JavaScript as well. If you have to write string with some special character like new line, colon etc, code becomes ugly. Let’s see a quick example

Here we can see that to write a text in two lines, we have to write a newline character (\n) at the right place, we cannot simply write it in two lines as it appears in output so actually you cannot visualize the output until you run it. Or you have other options to break it into multiple strings and use + operator as above which may look little similar but doesn’t look clean at all.

As mentioned earlier that there are times when we have to put special characters in the string like colon, quote, double quote, backslash etc and it becomes more ugly and confusing. To get it working, we need to add special escape character (\) every time it appears in the text as

var message = 
'Hello \'Brij\'\n, Did you use special chars in your new post \' Truthy and Falsy in JS\'?' 

Or if you want to write some regex which would be full of special characters.

Template Literals

Earlier there were three literals in JavaScript as Object ({}), Boolean (true or false) and string (” or “”) and starting from ES6, we have one more literal called template literal which is denoted by backtick character (“), it is mostly just below the escape character on keyboard.

Let’s see the above example using the template literal.

Here we can see that we have message appearing in IDE and console exactly same and we didn’t have any escape character.

Template literal also allows to have expressions which could be a normal variable or normal mathematical expression as

Here we can see the JavaScript code in the upper part and then output in the lower part. In the code, we used an expression three places: name, date object and normal addition of two numbers. Each expression should start with a dollar sign ($) as in the example. We can call any JavaScript function and can use other normal expressions like ternary operators.

This kind of capability has been added to C# some time back and seeing a similar feature in JavaScript made me very happy and couldn’t stop myself from sharing it with you all. (look at my signature 🙂 )

Cheers