Template Literals (The Modern way write strings in js)
What are Template Literals?
Template literals are simply strings with superpowers. They are the modern way of working with strings in JavaScript. Instead of using single or double quotes, template literals use backticks ( ). They allow you to write multi-line strings easily and include variables or expressions directly inside the string using ${}.
Normal Strings vs Template Literals
Without template literals, we usually rely on string concatenation to build dynamic strings:
const name = "Manas"; const age = 20;
const msg = "My name is " + name + " and I am " + age + " years old.";
This works, but the readability quickly becomes messy, especially in real-world projects where strings can get longer and more complex. Managing such code can be frustrating and error-prone.
With template literals, the same code becomes much cleaner and easier to understand:
const name = "Manas"; const age = 20;
const msg = `My name is \({name} and I am \){age} years old.`;
The output is exactly the same, but the code is far more readable and maintainable.
Multiline Strings
Handling multi-line strings with normal concatenation is also quite messy:
const text = "Line 1\n" + "Line 2\n" + "Line 3";
This requires manual line breaks and concatenation, which reduces clarity.
Template literals solve this neatly:
const text = `Line 1
Line 2
Line 3`;
This is much cleaner and closer to how the text actually looks, making it easier to read and write.
Syntax of Template Literals
Template literals use backticks and allow embedding variables or expressions directly using ${}. This makes string creation more intuitive and avoids complex concatenation.
const name = "Manas"; const age = 20;
const message = `My name is \({name} and I am \){age} years old.`;
console.log(message);
Here, variables are inserted directly into the string, making the code simpler, cleaner, and easier to maintain compared to traditional string concatenation.