Template Literals in JavaScript

Introduction
In modern javascript, template literals is the way to write code in strings using backticks (``), single quote (') and double quote ("").
This make string handling easy for developer. It makes your code better.
Problems with traditional string concatenation
Traditional string concatenation was done with the help of plus ( + ) operator. It was hard to write code as compared to template literals. It increases the chance of error in your code.
Example-
const name = "Abhishek";
const country = "India";
console.log("Hello! I am " + name + " from " + country + " which is in Asia.");
Issue with approach -
It is tough to write correct line of code due to the break of flow.
It is not scalable and hard to maintain.
Easy to miss commas, full stop or exclamation.
It is tough to read line of code by other developer too.
Issue with Multi lines -
const text = "This is line one.\n" +
"This is line two.\n" +
"This is line three.";
It is again hard to manage, write and read.
Template literal syntax
Template literals was in introduced in ES6. It is the modern way to write string and to do operations with strings in javascript.
Instead of single quotes ('') and double quotes (""), we use backticks (``), it is called as template literals.
const str = `This is template literals.`;
Embedding variables in strings
We can directly embedd variables in string using ${} symbol. This is called string interpolation.
Example -
const name = "Abhishek";
const country = "India";
console.log(`Hello! I am \({name} from \){country} which is in Asia.`);
// Hello! I am Abhishek from India which is in Asia.
Multi-line strings
It is also very easy to write and debug multi-line strings with the help of template literals.
Example -
const text = `This is line one.
This is line two.
This is line three.`;
No need of \n.
Clean and easy code.
It is maintainable and scalable.
Use cases in modern javascript
There are some of the use cases, which is mention below.
1. API url-
const userId = ncow932329dnc91m;
const url = `https://api.example.com/users/${userId}`;
2. Conditional -
const isLoggedIn = true;
const message = `User is ${isLoggedIn ? "online" : "offline"}`;
3. UI rendering -
const name = "Abhishek";
const App = `<h1>Hello ${name}!</h1>`;
Conclusion
In modern javascript, all developers are now writing their code with the help of template literals which are easy to read, write and debug.
This makes the code maintainable and scalable as compared to the code written with traditional way using plus (+) operator.



