The conditional IF-ELSEIF is an evolution of the conditionals IF and IF-ELSE, which allows us to evaluate multiple conditions and execute different blocks of code based on the result of each condition.
In natural language, the loop IF-ELSEIF means:
If this happens 🡆 do this
If not, but this other thing happens 🡆 do this
(… as many ‘if not, but’ as you want …)
And if none of the above 🡆 do this
The conditional IF-ELSEIF is a way to avoid nesting, using a more comfortable and readable syntax.
Its general syntax is as follows,
if (condition1)
{
// action to execute if condition1 is true
}
else if (condition2)
{
// action to execute if condition1 is false, and condition2 is true
}
...
[else if] ← as many `else if` as you want
...
else
{
// actions to execute if all previous conditions are false
}
Examples of IF-ELSEIF conditionals in different languages
Let’s look at an example of the conditional IF-ELSEIF. Suppose we have a measurement of the ambient temperature, and we want to display a result based on its value.
- If it is greater than 30º, it is hot 🔥
- If it is between 15º and 30º, the weather is nice 🌤️
- If it is less than 15º, it is cold ❄️
Let’s analyze what we want to do:
- A first IF checks if the temperature is greater than 30º 🔥
- A second ELSEIF checks if the temperature is greater than 15º. Since we have already ruled out that it is greater than 30º, this point will execute if the temperature is between 15-30º 🌤️
- The last ELSE will execute only if the temperature is less than 15 ❄️
Many languages provide an IF-ELSEIF structure. Let’s look at some examples:
This loop, in the case of C++, C#, Java, JavaScript, and Kotlin, for example, would have the following form.
if (temperatura > 30.0)
{
// display message 'It's hot!' 🔥
}
else if(temperatura > 15)
{
// display message 'The weather is nice' 🌤️
}
else
{
// display message 'It's cold!' ❄️
}
For example, in Python this same conditional would take the following form
if temperatura > 30.0:
# display message 'It's hot!' 🔥
elif temperatura > 15:
# display message 'The weather is nice' 🌤️
else:
# display message 'It's cold!' ❄️
Whereas, for example, in VB it would look like
If temperatura > 30.0 Then
' display message 'It's hot!' 🔥
ElseIf temperatura > 15 Then
' display message 'The weather is nice' 🌤️
Else
' display message 'It's cold!' ❄️
End If
The conditional IF-ELSEIF is a very powerful and readable control structure that allows us to make multiple decisions based on different conditions.
The only thing that might cause a bit of “confusion” at first is understanding that if you execute an ELSEIF, the previous conditions have already been ruled out (in the example, we saw this in the middle block. Which only executed if the temperature is between 15-30º).
But, in general, once you get the hang of it it is a quite readable structure. It is a good alternative to avoid nesting conditionals (which is something that should be reduced because they are harder to read).