Template Literals in JavaScript
Problems With Traditional String Concatenation
Before template literals, strings were combined using +.
Example
const name = "Ali"; const age = 22; const message = "My name is " + name + " and I am " + age + " years old."; console.log(message);
Problems
Hard to read
Too many + operators
Difficult with long strings
Poor formatting for multi-line text
What Are Template Literals?
Template literals are modern string syntax introduced in ES6.
They use:
` `
(backticks instead of quotes)
Basic Syntax
const name = "Ali";
const message = `Hello ${name}`;
console.log(message);
Output
Hello Ali
Embedding Variables in Strings
Use:
${variable}
This is called string interpolation.
Example
const product = "Laptop";
const price = 50000;
const result = `The ${product} costs ₹${price}.`;
console.log(result);
Output
The Laptop costs ₹50000.
String Interpolation Visualization
flowchart LR
A[Variable: Ali] --> B[${name}]
B --> C["Hello Ali"]
Before vs After Template Literals
Old Concatenation
const name = "Sara"; const text = "Welcome " + name + " to the platform.";
Template Literal Version
const name = "Sara";
const text = `Welcome ${name} to the platform.`;
Readability Comparison
Multi-Line Strings
Before template literals, multi-line strings were messy.
Old Way
const text = "Line 1\n" + "Line 2\n" + "Line 3"; console.log(text);
Template Literal Multi-Line String
const text = ` Line 1 Line 2 Line 3 `; console.log(text);
Output
Line 1 Line 2 Line 3
Multi-Line Visualization
Expressions Inside Template Literals
You can run JavaScript expressions directly.
Example
const a = 10;
const b = 20;
console.log(`Total: ${a + b}`);
Output
Total: 30
Real-World Use Cases
HTML Generation
const username = "Ali"; const html = `${username}
`; console.log(html);
API Messages
const status = 200;
console.log(`Request completed with status ${status}`);
Dynamic URLs
const userId = 15;
const url = `/users/${userId}`;
console.log(url);
Why Template Literals Are Preferred
Common Beginner Mistake
Using quotes instead of backticks.
Incorrect:
const name = "Ali";
console.log("Hello ${name}");
Correct:
const name = "Ali";
console.log(`Hello ${name}`);
Practice Exercise
const product = "Phone";
const price = 25000;
const message = `The ${product} costs ₹${price}.`;
console.log(message);
Key Takeaways
Final Notes
Template literals are heavily used in:
React
Node.js
APIs
HTML generation
Dynamic UI rendering
Modern JavaScript projects prefer template literals over traditional string concatenation because the code becomes cleaner and easier to maintain.
No attachments.
0 Comments
Sign in to join the conversation
No comments yet. Be the first to comment!