If and Else If Statements

If statements allow us to add conditional code to be executed based on certain conditions, this means we can add different routes or paths in our code. With if statements you can also add additional routes by using else if statements and else blocks of code. You can add as many else if statements as you like to one if statement, but you can only have one else block. The else block is at the end of the if/else if block of code, and is only executed if none of the other conditions are true.

Imagine you’re going shopping for eggs. If there are eggs you want to buy some.

The above code shows a basic if statement. The condition within an if statement must be a boolean statement, it must evaluate to either true or false.
Now, let’s think about adding additional routes in our code. What about if there are different quantity of eggs in the store, and we want to buy the biggest quantity.

Now our code will buy 12 or 6 eggs based on what is available. We could add as many else if block as we want here.

We can also have an else block at the end of our if statement. We can only have one else block and it must be at the end of our if else block. We could also have a single if block we an else block (e.g. without any else if blocks).

Remember though, our conditional block must start with one if statement and can only have one if statement. Also, there can only be one else block and it must be at the end of our conditions. Another thing to note, we can have a single if condition alone, the else if blocks are optional and so is the else block.

Leave a Reply