if/else and if/elseif

Without "elseif" syntax you would have to write chain if-statements for processing one of several possible outcomes this way:

if( str == "string1" ) {
   //handle first case
} else {
    if( str == "string2" ) {
       //handle second case
    } else {
       if( str == "string3" ) {
           //handle third case
       } else {
          //default case
       }
    }
 }

instead you can write

if( str == "string1" ) {
   //handle first case
} else if( str == "string2" ) {
   //handle second case
} else if( str == "string3" ) {
   //handle third case
} else {
   //default case
}

which is completely the same as the previous one, but looks much nicer and is much easier to read.


Situation a:

if( condition )
{
}
else
{
}

When the condition in the above statement is false, then the statements in the else block will always be executed.

Situation b:

if( condition )
{
}
else if( condition2 )
{
}
else
{
}

When 'condition' is false, then the statements in the else if block will only be executed when condition2 is true. The statements in the else block will be executed when condition2 is false.


Many languages have a grammer like this (here: ECMAScript Language Specification, so JavaScript):

IfStatement :
    if ( Expression ) Statement else Statement
    if ( Expression ) Statement

Statement :
    Block
    VariableStatement
    EmptyStatement
    ExpressionStatement
    IfStatement
    IterationStatement
    ContinueStatement
    BreakStatement
    ReturnStatement
    WithStatement
    LabelledStatement
    SwitchStatement
    ThrowStatement
    TryStatement

Block :
    { StatementListopt }

StatementList :
    Statement
    StatementList Statement

So the branches of an ifStatement may contain a block of statements (Block) or one of the other statements (other than Block). That means this is valid:

if (expr)
    someStatement;
else
    otherStatement;

And as StatementList may just contain a single statement, these examples are equivalent to the previous:

if (expr) {
    someStatement;
} else {
    otherStatement;
}

if (expr)
    someStatement;
else {
    otherStatement;
}

if (expr) {
    someStatement;
} else
    otherStatement;

And when we replace otherStatement by an additional IfStatement, we get this:

if (expr) {
    someStatement;
} else
    if (expr) {
        someOtherStatement;
    }

The rest is just code formatting:

if (expr) {
    someStatement;
} else if (expr) {
    someOtherStatement;
}