Nested if…else
Nested if…else statements in JavaScript allow us to create complex conditional logic by checking multiple conditions in a hierarchical manner. Each if statement can have an associated else block, and within each if or else block, you can nest another if…else statement. This nesting can continue to multiple levels, but it’s important to maintain readability and avoid excessive complexity.
Syntax:
if (condition1) {
// Code block 1
if (condition2) {
// Code block 2
} else {
// Code block 3
}
} else {
// Code block 4
}
Example: This example demonstrates how nested if…else statements can be used to handle different scenarios based on multiple conditions.
let weather = "sunny";
let temperature = 25;
if (weather === "sunny") {
if (temperature > 30) {
console.log("It's a hot day!");
} else if (temperature > 20) {
console.log("It's a warm day.");
} else {
console.log("It's a bit cool today.");
}
} else if (weather === "rainy") {
console.log("Don't forget your umbrella!");
} else {
console.log("Check the weather forecast!");
};
Output
It's a warm day.
Explanation: In this example, the outer if statement checks the weather variable. If it’s “sunny,” it further checks the temperature variable to determine the type of day it is (hot, warm, or cool). Depending on the values of weather and temperature, different messages will be logged to the console.
Conditional Statements in JavaScript
JavaScript conditional statements allow you to execute specific blocks of code based on conditions. If the condition is met, a particular block of code will run; otherwise, another block of code will execute based on the condition.
There are several methods that can be used to perform Conditional Statements in JavaScript.
Conditional Statement | Description |
---|---|
if statement | Executes a block of code if a specified condition is true. |
else statement | Executes a block of code if the same condition of the preceding if statement is false. |
else if statement | Adds more conditions to the if statement, allowing for multiple alternative conditions to be tested. |
switch statement | Evaluates an expression, then executes the case statement that matches the expression’s value. |
ternary operator | Provides a concise way to write if-else statements in a single line. |
Nested if else statement | Allows for multiple conditions to be checked in a hierarchical manner. |
This table outlines the key characteristics and use cases of each type of conditional statement. Now let’s understand each conditional statement in detail along with the examples.