35. Control Flow: Nested if Statements
A nested if statement is an if statement placed inside another if or else block. This is useful when a secondary condition must only be checked after a primary condition has already been met.
Example: Complex Access Check
Imagine a system where an account must be active, and if active, must also be an administrator to gain certain privileges.
javascript let accountActive = true; let userRole = 'admin';
if (accountActive) { console.log('Account is active.');
if (userRole === 'admin') {
console.log('Granting elevated privileges.');
} else {
console.log('Standard user access granted.');
}
} else { console.log('Access Denied. Account is inactive.'); }
// Output: // Account is active. // Granting elevated privileges.
Readability Caution
While nesting is powerful, too many levels of nesting (often called 'callback hell' in other contexts) can make code very difficult to follow. Try to use logical operators (&& or ||) to keep conditions on a single level when possible.