Overview of JavaScript Template Literals

JavaScript is an awesome programming language and also one of my favorite. It has so many cool features. In this article, I am going to cover one of that which is “Template literals” ( also known as Template strings ).

This feature has not been in JavaScript since the beginning. A version of JavaScript introduces this feature. ES6 comes up with so many new cool features. This is one of them. Actually, Template Literals is a new way to express string in JavaScript. It is much more readable and has lots of the facility. So, Let’s see some practical examples.

Here is an example of how we write a string in JS. Consider the following code.

let myString = "This is my string text";

But we write string using Template Literals inside the backticks instead of quotes or double-quotes. Consider the following example.

let myString = `This is my string text`;

The output of those two examples is the same. So, why we use this feature? To find out, let’s look at some examples.

// Variable for name
let myName = 'Jhon Doe';

// Old School Way
let greet1 = 'Hello, ' + myName;
console.log(greet1); // Output = Hello Jhon Doe

// Template Literals Way
let greet2 = `Hello, ${myName}`;
console.log(greet2); // Output = Hello Jhon Doe

Both outputs are the same. So, the difference is how to concatenate the value in our final variable.
It is very easy to concatenate a variable with a string using a Template Literals. Just put your variable inside curly braces and don’t forget to put a $ sign before the braces. It’s a bit cleaner way also. One the other hand, concatenate a string in a previous way is more difficult when you have more than one variable. Keeping the balance of (+) sign and quotes balance is a bit difficult. Consider the following code.

// Variables
let myName = 'Jhon Doe';
let myAge = 15;
let myCountry = 'USA';

// Old School Way
let sentence1 = 'My name is ' + myName + ' and I am ' + myAge + ' years. I am from the ' + myCountry + '.';
console.log(sentence1); // Output = My name is Jhon Doe and I am 15 years. I am from the USA.

// Template Literals Way
let sentence2 = `My name is ${myName} and I am ${myAge} years. I am from the ${myCountry}.`;
console.log(sentence2); // Output = My name is Jhon Doe and I am 15 years. I am from the USA.

So, the difference is very clear. Another cool thing of Template Literals is that we can use any kind of JavaScript expression inside the curly braces. We can also use JS code here. It works perfectly. Consider the following examples.

// Example One
console.log(`2 plus 2 = ${2 + 2}`); // Output = 2 plus 2 = 4

// Example Two
let myName = '';
let greet = `Hello, ${(myName === '') ? 'World' : myName}!`;
console.log(greet); // Output = Hello, World!

Template Literals is very easy and useful. Finally, I hope you got an overview of JavaScript Template Literals.

Happy Coding 🙂