Template Literals in JavaScript Explained with Examples
A beginner-friendly guide to writing cleaner, more readable JavaScript strings using ES6 Template Literals.

Before we know what template literals are, it is important to know why template literals were introduced and what was used before template literals was introduced. What were the problems with the earlier method? Let's first discuss that.
Why Template Literals was introduced?
Before template literals was introduced, developers used the + operator to join strings.
let name = "Ayush";
console.log("Name: "+ name);
//Output -- Name: Ayush
Problems with + Operator
1. Poor Readability
As strings become longer, concatenation becomes messy.
const text =
"Hello " +
name +
", welcome to our website. Your account balance is " +
balance +
" rupees.";
2. Multi Line string
before Template Literals
const message =
"Line 1\n" +
"Line 2\n" +
"Line 3";
we had to use /n for every line.
3. Easy to make mistakes
missing spaces
let name = "Ayush"
console.log("Hello" + name)
//Output -- HelloAyush
these types of mistakes were very common
What are Template Literals?
Template literals were introduced with ES6 in 2015.
Now instead of ( ' ' ) and ( " " ) back ticks ( ` ` ) are used to define a string and this allowed writing a variable inside a string ( string interpolation) without using the operator.
const name = "Ayush";
const message = `Hello ${name}`;
console.log(message);
//Output -- Hello Ayush
Syntax of template literals
Basic syntax
`Text here`
With variable
const language = "JavaScript";
console.log(`I am learning ${language}`);
//Output -- I am learning JavaScript
Multi Line String
template literals allow you to write multi-line strings directly.
Without Template Literals:
const text =
"Hello\n" +
"Welcome\n" +
"To JavaScript";
With Template Literals:
const text = `
Hello
Welcome
To JavaScript
`;
Real-World use cases
Generating Dynamic Messages
const username = "Ayush";
const greeting = Welcome back, ${username}!;
Building URLs
const userId = 123;
const url = /users/${userId};
Dynamic CSS Classes
const active = true;
const className = `btn ${active ? "active" : ""}`;
Used extensively in React.
Key Takeaways
Template literals were introduced in ES6.
They use backticks ( ` ` ) instead of quotes.
${}allows string interpolation.They improve readability compared to
+concatenation.Multi-line strings become much easier to write.
Widely used in React, URLs, and dynamic UI rendering.

