Template Literals
A Better Way to Write Strings
Before ES6 (2015), if you wanted to combine variables with text, you had to use the + operator. This is called string concatenation, and it gets messy very quickly.
// The Old Way
let firstName = "Himanshu";
let job = "Developer";
let greeting = "Hello, my name is " + firstName + " and I am a " + job + ".";
Enter Template Literals
Template literals use backticks (`) instead of quotes. They allow you to inject variables directly inside the string using the ${variable} syntax. This is called String Interpolation.
// The Modern Way
let firstName = "Himanshu";
let job = "Developer";
let greeting = `Hello, my name is ${firstName} and I am a ${job}.`;
This is much cleaner and much easier to read!
Multi-Line Strings
Another massive advantage of template literals is that they support multi-line strings natively. With normal quotes, you'd have to use \n to create a new line.
let message = `This is line one.
This is line two.
This is line three.`;
Template literals are the absolute standard for writing dynamic strings in modern React and Next.js applications.
💡 Himanshu's Tip:
Always use backticks when you are injecting data into a string! It prevents the annoying bugs where you forget to add a space before the closing quote during concatenation.
Interview Questions
- What character is used to create a Template Literal?
- How do you inject an expression or variable inside a Template Literal?
- Can you perform math operations inside a
${}block?