else if Statements

By: Dusty Arlia
Published on October 24, 2012
Last Updated on Wednesday, July 08, 2015 at 8:38 PM
Total Updates: 6

else if statements come in handy when you have multiple conditions, options, or questions to ask in your program. else if statements follow if statements and come before a final else statement. You can have zero or more else if statements follow your initial if statement, but you can only have a single else statement come after your else if statements (if you don't have any else/if clauses, the else clause is optional). Here is the basic syntax of an if statement with multiple else if clauses:

if (/*condition*/){
// option 1
} else if (/*condition*/) {
//option 2
} else if (/*condition*/) {
//option 3
} else {
//option 4

And here's an example:

var pulledString = 4;

if (pulledString == 1) {
alert("I pulled string 1");
} else if (pulledString == 2) {
alert("I pulled string 2");
} else if (pulledString == 3) {
alert("I pulled string 3");
} else {
alert("I pulled string 4");

switch statements should be used in place of multiple else if statements in certain situations. switch statements are a better option when all of the branches of your conditional statement rely on the value of the same expression. else if statements require evaluating a condition at every branch. When a switch statement executes, it evaluates the expression that follows the switch keyword first. After that, the switch statement evaluates the case expressions. If a case label has a matching expression, then that case gets executed.