Nested If-Else Statements
In JavaScript, nested if-else statements are used to handle complex conditions by combining multiple if-else statements. With nested if-else statements, you can have one if-else statement inside another if-else statement.
Nested if-else statements allow you to test for more specific conditions within the scope of a broader condition. This enables you to write logic that considers multiple factors.
Here's an example to illustrate nested if-else statements:
1const age = 20;
2const hasLicense = true;
3
4if (age >= 18) {
5 if (hasLicense) {
6 console.log('You are eligible to drive.');
7 } else {
8 console.log('You are eligible to apply for a license.');
9 }
10} else {
11 console.log('You are not eligible to drive or apply for a license.');
12}
In this example, we first check if the age
is greater than or equal to 18. If it is, we then check if the hasLicense
variable is true. Depending on the values of these variables, different messages will be logged to the console.
Nested if-else statements can be used to create more complex logic and handle multiple conditions in a program. They provide a way to evaluate different scenarios and execute specific blocks of code based on those scenarios.
Now it's your turn to practice using nested if-else statements. Feel free to modify the code example above and see how the output changes. You can also try creating your own nested if-else statements to solve different problems!
xxxxxxxxxx
// Example of nested if-else statements
const age = 20;
const hasLicense = true;
if (age >= 18) {
if (hasLicense) {
console.log('You are eligible to drive.');
} else {
console.log('You are eligible to apply for a license.');
}
} else {
console.log('You are not eligible to drive or apply for a license.');
}