📚Template Literals in JavaScript
❓What is Template Literals
Template Literals are the way of writing "strings" using the backticks (``) instead of using the quotes.
For Example:-
const name = "Pratik";
const age = 10;
console.log(`Hello \({name}, your age is \){age}`)
Output:-
Hello Pratik, your age is 10;
If you want to do the same task by using the normal string then you have to use the add operator i.e. string concatenation method.
For Example:-
const name = "Pratik"
const age = 10;
console.log("Hello " + name + ", your age is " +age)
Output:-
Hello Pratik, you age is 10
Now see the difference between this two,
The syntax of the Template Literals is very easy and clean
If you see properly, in Template Literals we don't have to gives the spacing but in the normal string we have to give the spaces which is very boring job and it will not good.
Because of this reasons we use the Templates Literals.
🔥Different Techniques to use the Template Literals
🔸 Basic Variable Interpolation
const name = "Pratik"
console.log(`Hello ${name}`)
Otuput:-
Hello Pratik
🆚 Normal
const name = "Pratik"
console.log("Hello "+ name )
Output:-
Hello Pratik
🔸 Multiple Variables
see the starting example .
🔸 Expressions Inside ${}
const a = 10;
const b = 20;
console.log(`Sum : ${a+b}`);
Output:-
Sum: 30
🆚 Normal
const a = 10;
const b = 20;
console.log("Sum: " + (a+b) )
Output :-
Sum: 30
🔸 Multi-line Strings
You can simply add the multiple lines.
const text = `Hello
World`
🆚 Normal
- You have to use the "\n" character every time for the new Line.
const text = "Hello\n world"
🔸 Nested Templates
const user = {
name: "pratik",
role: "admin",
isActive: true
};
const html = `
<div>
<h1>\({`User: \){user.name.toUpperCase()}`}</h1>
<p>${user.isActive
? `Status: \({`🟢 ACTIVE (\){user.role.toUpperCase()})`}`
: `Status: đź”´ INACTIVE`}
</p>
</div>
`;
console.log(html);
🆚 Normal
To done this task by using the Normal methods is very difficult and makes the structure messy.
🔥Comparison Table
| Feature | Template Literals | Normal Strings |
|---|---|---|
| Syntax | ` ` |
" " or ' ' |
| Variables | ${} |
+ |
| Readability | ✅ High | ❌ Low (messy) |
| Multi-line | ✅ Easy | ❌ Difficult |
| Expressions | ✅ Direct | ❌ Needs () |
| Modern Usage | ✅ Yes | ❌ Old way |
“Stop breaking yourself with + again and again…
I am Template Literal — clean, powerful, and modern.
I don’t complicate things, I express them.
Just use ${} and let your code speak clearly.
Upgrade yourself… because messy code is a past,
and I am the future.” 🚀
