Applying else if for Multiple Conditions
メニューを表示するにはスワイプしてください
Now, let's explore a scenario where multiple conditions come into play:
1234567891011121314151617let a = 11; if (a > 15) { console.log('greater than 15'); } if (a > 10) { console.log('greater than 10'); } if (a > 5) { console.log('greater than 5'); } if (a > 0) { console.log('greater than 0'); }
In this example, the variable a is greater than 10, but other messages like "greater than 5" and "greater than 0" are also being printed. This isn't the desired behavior when you want to execute only one condition.
The else statement wouldn't work well here due to multiple conditions.
Introducing else if
The else if construct provides a solution for selecting a specific code block within a series of conditions:
if (condition) {
// First `if` code block
} else if (condition) {
// First `else-if` code block
} else if (condition) {
// Second `else-if` code block
}
As you can see, the else-if statement is straightforward, with an if statement followed by it:
if (condition) {
// Code block
} else if (condition) {
// Repeat the `if` syntax
}
Let's apply this to our example:
1234567891011let a = 11; if (a > 15) { console.log("greater than 15"); } else if (a > 10) { console.log("greater than 10"); } else if (a > 5) { console.log("greater than 5"); } else if (a > 0) { console.log("greater than 0"); }
Now, we've created a sequence of conditions. When at least one if condition becomes true, the chain is interrupted.
Note
This structure is useful when you only need one condition to be satisfied.
Adding else
You can also add an else statement after the condition chain.
Let's modify our example:
12345678910111213let a = -61; if (a > 15) { console.log("greater than 15"); } else if (a > 10) { console.log("greater than 10"); } else if (a > 5) { console.log("greater than 5"); } else if (a > 0) { console.log("greater than 0"); } else { console.log("No condition is satisfied"); }
フィードバックありがとうございます!
AIに質問する
AIに質問する
何でも質問するか、提案された質問の1つを試してチャットを始めてください