Template Literals in JavaScript
Introduction
Working with strings is very common in JavaScript. Earlier, we used string concatenation to combine text and variables. But it often made code messy and hard to read.
To solve this, JavaScript introduced template literals.
Problems with Traditional String Concatenation
Before template literals, we used + to join strings.
Example
const name = "John";
const age = 25;
const message = "My name is " + name + " and I am " + age + " years old.";
console.log(message);
Issues:
Hard to read
Too many
+signsDifficult to manage in long strings
Template Literal Syntax
Template literals use backticks ( ) instead of quotes.
Example
const message = `Hello World`;
Embedding Variables in Strings
With template literals, we can directly insert variables using ${}.
Example
const name = "John";
const age = 25;
const message = `My name is \({name} and I am \){age} years old.`;
console.log(message);
This is called string interpolation.
Multi-line Strings
Earlier, multi-line strings were difficult.
Old Way
const text = "This is line 1\n" +
"This is line 2";
Template Literals Way
const text = `This is line 1
This is line 2`;
Much cleaner and easier to read.
Use Cases in Modern JavaScript
1. Dynamic Messages
const user = "Aman";
console.log(`Welcome, ${user}!`);
2. HTML Templates
const title = "Hello";
const html = `
<div>
<h1>${title}</h1>
</div>
`;
3. Expressions Inside Strings
const a = 5;
const b = 10;
console.log(`Sum is ${a + b}`);
Before vs After Comparison
Before
"Total price is " + (price * quantity)
After
`Total price is ${price * quantity}`
Diagram Ideas
String Interpolation Visualization
`Hello ${name}`
↓
"Hello John"
Before vs After
Old → "Hello " + name
New → `Hello ${name}`
Why Template Literals Are Better
Cleaner syntax
Easy to read
Supports multi-line strings
Allows expressions inside strings
Reduces errors
Conclusion
Template literals make string handling simple and powerful in JavaScript. They improve readability and are widely used in modern web development. Once you start using them, you will rarely go back to old string concatenation.