We've explored how 'if', 'else if', and 'else' statements allow our programs to make choices. Now, let's dive into how we can make these decisions even more sophisticated by combining them. This is where 'nested' and 'complex' conditional statements come into play.
Imagine a scenario where a decision depends on multiple factors, and the outcome of one factor influences how we evaluate another. This is the essence of nesting. A nested conditional statement is simply an 'if', 'else if', or 'else' statement placed inside another conditional statement. Think of it like a set of Russian nesting dolls; one decision contains another.
let age = 25;
let hasLicense = true;
if (age >= 18) {
console.log('You are old enough to drive.');
if (hasLicense) {
console.log('You can get on the road!');
} else {
console.log('You need to obtain a license first.');
}
} else {
console.log('You are too young to drive.');
}In this example, the outer 'if' checks if the person's age is 18 or over. Only if this condition is true do we proceed to the inner 'if' statement, which then checks if they have a license. This allows us to create a more granular set of conditions and outcomes.
graph TD
A[Is age >= 18?] -->|Yes| B{Does person have a license?}
A -->|No| C[Too young to drive]
B -->|Yes| D[Can get on the road!]
B -->|No| E[Need to obtain a license]
Beyond nesting, we can also create more complex conditions within a single 'if' or 'else if' statement using logical operators. The two most common are:
- AND (&&): Both conditions must be true for the overall expression to be true.
- OR (||): At least one of the conditions must be true for the overall expression to be true.
Let's revisit our driving example, but this time using the 'AND' operator to combine age and license checks into a single condition.
let age = 20;
let hasLicense = true;
if (age >= 18 && hasLicense) {
console.log('You can drive!');
} else if (age >= 18 && !hasLicense) {
console.log('You are old enough but need a license.');
} else {
console.log('You are too young to drive.');
}