JavaScript ES6 – What are Template Literals

JavaScript ES6 – What are Template Literals

Since the beginning of time JavaScript developers are using single quotes and double quotes to create strings. However, ES6 specification came with template literals which is more elegant way of creating strings. In this post, we’re going to understand what template literals are? And how to use them within your applications to improve code readability?

Basic Usage:

We usually use single or double quotes to create strings.

const name1 = 'sam';
const name2 = "harry";

When it comes to template literals we need to use the back tick key located on the upper let corner of your keyboard. A basic example of template literals is as follows.

const name3 = `john`;

Line Breaks:

Before ES6, we had to use \n to maintain line breaks between our strings. The following code will log the string in 2 lines.

const myText = 'I am on line one. \n I am on line two';
console.log(myText);

We can do the same using template literals in much a simpler way.

const myText = `I am on line one.
I am on line two.`;
console.log(myText);

Note that template literals are space sensitive.

const myText = `I am on line one.
                I am on line two.`;
console.log(myText);

The above code will produce the following output in the console.

I am on line one.
                I am on line two.

Interpolation:

In order to interpolate variables in variables or expression in traditional strings, you would use following syntax:

const num = 2;
console.log('Square of ' + num + ' is ' + (num * num));

You can do the same thing in much simpler way using template literals.

const num = 2;
console.log(`Square of ${num} is ${num * num}`);

As you can see in the above code, you can simply add your variables or expressions to dollar sign followed by curly braces in order to interpolate them.

Recommended: How To Inject Document Object In Angular Service

I hope you found this post useful. In case if you’ve any query or feedback feel free to drop a comment.

One thought on “JavaScript ES6 – What are Template Literals”

Leave a Reply

Your email address will not be published. Required fields are marked *