An if statement tests whether the result of an expression is true and then executes a statement block. This is a conditional execution.
If statements can also be used for branching, that is, for executing one of a number of statements depending on the pre-conditions* of the statement block to be executed.
if (condition A) --> execute statement 1; if (condition B) --> execute statement 2; if (condition C) --> execute statement 3; etc.
*) A program is given some data to process. The pre-condition is the state of the data before the program is executed. The post-condition is the state of the data after the program is executed. The same applies to any blocks of code within a program.
Let us assume we want to test the value of a variable and branch our script accordingly. If our code were structured like the example, the variable would be tested after each if statement. If we are looking for only one particular condition, however, such code would not necessarily be very efficient. If condition A is true, why do we need to test conditions B and C?
Programming languages include a conditional construction that takes care of such cases:
if (condition A) { statement 1 } else if (condition B) { statement 2 } else if (condition C) { statement 3 } etc.
The if / else if construction groups conditional statements in a block. if is a key word that initiates a conditional block; else if identifies the conditional statement to belong the preceding if or else if statement. (If there is none, you'll get an error and your script crashes.)
Just as in the simple if statement, every expression after the if is evaluate, however, only until a true condition is found. If this is the case, the corresponding statement block is executed and the script continues after the if / else if block, without testing further conditions.