Language: EN


The IF-ELSEIF conditional

The conditional IF-ELSEIF is an evolution of the conditionals IF and IF-ELSE, which allows us to evaluate multiple conditions and execute different code blocks based on the result of each condition.

In natural language, the IF-ELSEIF loop means:

If this happens 🡆 do this
If not, but this other happens 🡆 do this
(…optionally several ‘if not, but’)
And if none of the above 🡆 do this

The IF-ELSEIF conditional is a way to avoid nesting, using a more comfortable and easy-to-read 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] ← all the `else if` you want
	// action to execute if all previous conditions are false

Examples of IF-ELSEIF conditionals in different languages

Let’s see an example of the IF-ELSEIF conditional. Let’s suppose we have a measurement of the ambient temperature, and we want to show a result based on its value.

  • If it is greater than 30º, it is hot 🔥
  • If it is between 15º and 30º, it’s good weather 🌤️
  • If it is less than 15º, it’s cold ❄️

Let’s analyze what we want to do:

  • A first IF checks if the temperature is greater than 30º 🔥
  • A second ELSEIF checks that the temperature is greater than 15º. Since we have already ruled out that it is greater than 30º, this point will be executed if the temperature is between 15-30º 🌤️
  • The last ELSE will be executed only if the temperature is less than 15 ❄️

Many languages provide an IF-ELSEIF structure. Let’s see some examples:

This loop, in the case of C++, C#, Java, Kotlin, and JavaScript, for example, would have the following form.

if (temperature > 30.0)
	// show message 'It's hot!' 🔥
else if(temperature > 15)
	// show message 'It's good weather' 🌤️
	// show message 'It's cold!' ❄️

For example, in Python this same conditional would have the following form

if temperature > 30.0:
    # show message 'It's hot!' 🔥
elif temperature > 15:
    # show message 'It's good weather' 🌤️
    # show message 'It's cold!' ❄️

While, for example, in VB it would be

If temperature > 30.0 Then
    ' show message 'It's hot!' 🔥
ElseIf temperature > 15 Then
    ' show message 'It's good weather' 🌤️
    ' show message 'It's cold!' ❄️
End If

The IF-ELSEIF conditional is a very powerful and readable control structure that allows us to make multiple decisions based on different conditions.

The only thing that can cause a bit of “mess” at first is understanding that if you run an ELSEIF, the previous conditions have already been ruled out. In the example we have seen it in the middle block. Which only ran if the temperature was between 15-30º.

But, in general, once you get the hang of it, it’s a fairly readable structure. It is a good alternative to avoid nesting conditionals, which is something that should be reduced because they are harder to read.