Why should I use an else if to chain an if statement instead of an if?


#1

Question

When I want to use multiple if statements, when should I chain an else if to the if or just use multiple if statements?

Answer

When you have many if statements one after the other, the code will run through each if statement and check the condition inside the if. If the condition evaluates to true, then it will enter the if. Then it will check the next if condition.

When you have an else if come after the if, it will only be evaluated if the if or else if before it evaluates to false.

For example:

let x = 1;
if (x === 1) {
   x += 1
}
if (x < 3) {
   x += 2
}

x will evaluate to 4 at the end, because the first condition is true and the second condition is true.

Now let’s look at the example where we have chained else if statements

let x = 1;
if (x === 1) {
   x += 1 
} else if (x < 3) {
   x += 2
}

In the example above, x will be 2 at the end because the first condition is satisfied and the second condition will not be evaluated (even if it is true).