Course Content
Introduction to JavaScript
Introduction to JavaScript
else if
Now, let's explore a scenario where multiple conditions come into play:
let 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:
As you can see, the else-if
statement is straightforward, with an if
statement followed by it:
Let's apply this to our example:
let 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:
let 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"); }
Thanks for your feedback!