Introduction
A Nested if Statement is an if statement placed inside another if statement. It is used when a decision depends on multiple levels of conditions.
The outer if statement checks the first condition. If that condition is true, the program enters the outer block and then evaluates the inner if statement. This allows JavaScript programs to make more detailed and structured decisions.
Nested if statements are commonly used in real-world applications such as login systems, banking applications, e-commerce websites, role-based access control, and automation testing frameworks.
For automation engineers, nested if statements are useful for validating multiple conditions, checking element visibility before performing actions, handling API responses, and verifying complex test scenarios.
What is a Nested if Statement?
A nested if statement means placing one if statement inside another if statement.
The inner if statement executes only if the outer if condition is true.
Syntax
if (condition1) {
if (condition2) {
// Code executes if both conditions are true
}
}
Flow of Execution
Start
│
▼
Condition 1?
│
┌─┴─────────────┐
│ │
True False
│ │
▼ ▼
Condition 2? End
│
┌─┴─────────────┐
│ │
True False
│ │
▼ ▼
Execute Code End
Why Do We Use Nested if Statements?
Nested if statements help developers:
Check multiple dependent conditions.
Handle complex business rules.
Improve decision-making.
Validate data step by step.
Control program execution more precisely.
Basic Example
let age = 25;
if (age >= 18) {
if (age >= 21) {
console.log("Eligible for all activities.");
}
}
Output
Eligible for all activities.
The second condition is checked only because the first condition is true.
Example with Student Marks
let marks = 82;
if (marks >= 35) {
if (marks >= 75) {
console.log("Passed with Distinction");
}
}
Output
Passed with Distinction
Login Verification Example
let username = "admin";
let password = "admin123";
if (username === "admin") {
if (password === "admin123") {
console.log("Login Successful");
}
}
Output
Login Successful
Real-World Example
Suppose an ATM checks both the account balance and the withdrawal amount.
let balance = 5000;
let withdrawal = 2000;
if (balance > 0) {
if (withdrawal <= balance) {
console.log("Transaction Successful");
}
}
Output
Transaction Successful
Another example:
let loggedIn = true;
let isPremiumUser = true;
if (loggedIn) {
if (isPremiumUser) {
console.log("Access Premium Features");
}
}
Output
Access Premium Features
Automation Testing Example
Automation engineers frequently use nested if statements to validate multiple conditions before performing an action.
Playwright Example
const isVisible = await page.locator("#loginButton").isVisible();
if (isVisible) {
const isEnabled = await page.locator("#loginButton").isEnabled();
if (isEnabled) {
await page.locator("#loginButton").click();
}
}
The button is clicked only if it is both visible and enabled.
Selenium Example
let title = await driver.getTitle();
if (title === "Dashboard") {
let url = await driver.getCurrentUrl();
if (url.includes("dashboard")) {
console.log("Dashboard Verified");
}
}
Output
Dashboard Verified
API Testing Example
let statusCode = 200;
let responseTime = 450;
if (statusCode === 200) {
if (responseTime < 1000) {
console.log("API Performance Passed");
}
}
Output
API Performance Passed
User Role Validation
let isLoggedIn = true;
let role = "Admin";
if (isLoggedIn) {
if (role === "Admin") {
console.log("Administrator Access Granted");
}
}
Output
Administrator Access Granted
Nested if with else
You can combine nested if statements with else.
let age = 16;
if (age >= 18) {
if (age >= 21) {
console.log("Eligible for all activities");
} else {
console.log("Adult but under 21");
}
} else {
console.log("Minor");
}
Output
Minor
Nested if vs Logical Operators
Instead of:
if (age >= 18) {
if (citizen) {
console.log("Eligible");
}
}
You can write:
if (age >= 18 && citizen) {
console.log("Eligible");
}
Both approaches produce the same result.
However, nested if statements are useful when the second condition should be checked only after the first one succeeds or when additional logic is needed inside each level.
Common Mistakes
Creating Too Many Nested Levels
Incorrect:
if (a) {
if (b) {
if (c) {
if (d) {
console.log("Done");
}
}
}
}
Deep nesting makes code difficult to read and maintain.
Forgetting Curly Braces
Always use braces, even if there is only one statement inside each block.
Using Nested if When a Logical Operator Is Enough
Instead of:
if (loggedIn) {
if (isAdmin) {
console.log("Access Granted");
}
}
Use:
if (loggedIn && isAdmin) {
console.log("Access Granted");
}
This version is shorter and easier to read.
Best Practices
Avoid Deep Nesting
Keep nesting to a minimum. Excessive nesting reduces readability.
Use Logical Operators When Appropriate
If multiple conditions can be evaluated together, use && or || instead of unnecessary nested if statements.
Use Meaningful Variable Names
Instead of:
if (a)
Use:
if (isUserLoggedIn)
Descriptive names make the code easier to understand.
Keep Each Block Focused
Each nested block should perform a single, well-defined task.
Conclusion
Nested if statements allow JavaScript programs to evaluate multiple dependent conditions in a structured manner. They are useful when one condition must be satisfied before checking another, making them ideal for implementing complex business rules and multi-step validations.
For automation engineers, nested if statements are valuable for verifying UI states, checking API responses, validating user roles, and ensuring that actions are performed only when all required conditions are met.
Frequently Asked Questions (FAQs)
What is a nested if statement?
A nested if statement is an if statement placed inside another if statement to evaluate multiple dependent conditions.
What is the syntax of a nested if statement?
if (condition1) {
if (condition2) {
// Code
}
}
When should I use nested if statements?
Use nested if statements when one condition should be evaluated only after another condition has been satisfied.
Can nested if statements include else blocks?
Yes. Each if statement can have its own else block.
Why are nested if statements useful in automation testing?
Automation engineers use nested if statements to validate multiple conditions, such as checking whether an element is visible before verifying that it is enabled, validating API responses before checking response time, and implementing multi-step test logic.
Key Takeaways
A nested
ifstatement is anifstatement inside anotherifstatement.The inner
ifexecutes only if the outerifcondition is true.Nested
ifstatements are useful for multi-level decision-making.They help implement complex business logic.
Use logical operators (
&&and||) when simple condition combinations are sufficient.Avoid excessive nesting to keep code readable.
Always use curly braces for clarity and maintainability.
Nested
ifstatements are widely used in web development and automation testing.Use meaningful variable names to improve readability.
Mastering nested
ifstatements helps build reliable and maintainable JavaScript applications.
