-
Hajipur, Bihar, 844101
Hajipur, Bihar, 844101
JS Basics
JS Variables & Operators
JS Data Types & Conversion
JS Numbers & Math
JS Strings
JS Dates
JS Arrays
JS Control Flow
JS Loops & Iteration
JS Functions
JS Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts
JavaScript string templates, also known as template literals, are a modern and powerful way to work with strings in JavaScript. Unlike traditional strings, template literals provide a flexible way to embed expressions, handle multi-line content, and build dynamic text without messy concatenation. They improve readability, reduce errors, and make code easier to maintain. Understanding template literals is essential for building interactive, dynamic, and professional web applications.
In this chapter, you will learn what string templates are, how to use them effectively, practical examples with real-world scenarios, common mistakes, best practices, and real-world applications.
String templates are strings enclosed in backticks (`) instead of single (') or double (") quotes. They allow developers to:
Embed variables or expressions directly within strings
Create multi-line strings without using escape sequences (\n)
Improve readability for long or dynamic strings
Avoid complex concatenation using the + operator
The syntax for embedding expressions is:
`${expression}`
For example:
let student = "Ananya";
let age = 22;
let message = `Hello ${student}, you are ${age} years old.`;
console.log(message); // Hello Ananya, you are 22 years old.
Here, ${student} and ${age} are placeholders that dynamically insert values into the string.
String templates simplify string creation and manipulation. They are important because they:
Reduce errors caused by mismatched quotes or missing plus signs
Allow direct embedding of variables, expressions, and function calls
Enable clean multi-line text without using \n
Improve readability and maintainability of code
Make it easier to work with dynamic content like HTML, emails, or reports
Using template literals helps developers write cleaner, more organized, and less error-prone code compared to traditional concatenation methods.
Previously, creating multi-line strings required using newline characters (\n) and concatenation:
let text = "Hello Ananya,\nWelcome to the JavaScript course.\nEnjoy learning!";
With template literals, multi-line strings are straightforward and preserve the format:
let text = `Hello Ananya,
Welcome to the JavaScript course.
We hope you enjoy learning JavaScript!`;
console.log(text);
This approach is especially useful when generating emails, messages, HTML, or long textual content.
Template literals allow embedding expressions directly within ${} placeholders. These expressions can include calculations, function calls, or even ternary operations.
let student = "Mira";
let marks = 85;
let message = `${student} scored ${marks + 5} marks in the exam.`;
console.log(message); // Mira scored 90 marks in the exam.
You can also embed more complex expressions:
let a = 10;
let b = 15;
console.log(`The sum of a and b is ${a + b}`); // The sum of a and b is 25
This eliminates the need for multiple concatenations and improves readability.
let student1 = "Riya";
let student2 = "Ananya";
let student3 = "Diya";
let greeting = `Hello ${student1}, ${student2}, and ${student3}! Welcome to the class.`;
console.log(greeting);
This example demonstrates embedding multiple variables directly into a string without using concatenation.
let student = "Mira";
let score = 92;
let total = 100;
let result = `${student} scored ${score} out of ${total}.`;
console.log(result);
function calculateGrade(marks) {
return marks >= 90 ? "A+" : marks >= 80 ? "A" : "B";
}
let student = "Sneha";
let marks = 87;
let report = `${student} received grade ${calculateGrade(marks)} in the exam.`;
console.log(report);
Template literals are particularly useful for generating HTML dynamically:
let student = {
name: "Diya",
age: 21,
course: "JavaScript"
};
let html = `
<div class="student-card">
<h2>${student.name}</h2>
<p>Age: ${student.age}</p>
<p>Course: ${student.course}</p>
</div>
`;
console.log(html);
This approach reduces the need for complex string concatenation and makes HTML generation much cleaner.
let student = "Riya";
let email = `
Dear ${student},
Congratulations on completing the JavaScript course!
We are proud of your achievement.
Best regards,
The Teaching Team
`;
console.log(email);
let students = ["Ananya", "Riya", "Mira", "Diya"];
let message = `The students enrolled in the course are: ${students.join(", ")}.`;
console.log(message);
This example shows how template literals can integrate arrays and array methods directly into strings.
let student = "Sneha";
let marks = 75;
let message = `${student} has ${marks >= 80 ? "passed with distinction" : "passed"} the exam.`;
console.log(message);
Using conditional expressions within template literals allows dynamic content changes without additional if statements.
Using single or double quotes instead of backticks for template literals
Forgetting to wrap expressions inside ${} placeholders
Overcomplicating expressions inside template literals; prefer using variables or functions
Mixing old string concatenation with template literals unnecessarily
Forgetting that template literals preserve whitespace and line breaks, which may affect formatting in certain contexts
Use template literals for all dynamic strings in modern JavaScript code
Keep expressions inside ${} simple and readable
Use functions or variables instead of embedding complex logic directly
Leverage multi-line templates for HTML, emails, or long messages
Avoid combining template literals with old concatenation techniques
Template literals are widely used in:
Displaying dynamic content in web pages
Creating personalized messages, emails, or notifications
Generating dynamic HTML or markup for templates
Logging debug messages with embedded variables
Constructing complex strings for reports, messages, or APIs
Handling multi-line text efficiently without escape sequences
JavaScript string templates, or template literals, provide a modern and clean way to handle strings dynamically. They allow embedding variables, expressions, arrays, and functions directly into strings. Multi-line strings, dynamic HTML generation, conditional content, and improved readability make template literals a powerful tool for modern web development. Mastering template literals reduces errors, simplifies code, and enhances maintainability in real-world applications.
Q1. How do you include a variable user = "Alice" in the string "Welcome, Alice!" using a template literal?
Q2. How do you print a multiline message using a single template string?
Q3. What is the output of this code: `2 + 3 = ${2 + 3}`?
Q4. How can you display "Total: $100" by inserting a variable amount = 100 into the string?
Q5. How do you write "Today is Sunday" using a variable day = "Sunday" and a template literal?
Q6. How do you call a function getUserName() inside a template literal to greet the user?
Q7. What happens if you use single or double quotes instead of backticks with ${}?
Q8. How do you use a template literal to combine two variables: first = "Good" and second = "Morning"?
Q9. Write a string using template literals to display "10 * 2 = 20" by evaluating inside ${}.
Q10. How do you show "Length of name is 4" using a variable name = "John"?
JS Basics
JS Variables & Operators
JS Data Types & Conversion
JS Numbers & Math
JS Strings
JS Dates
JS Arrays
JS Control Flow
JS Loops & Iteration
JS Functions
JS Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts
