When should I use multiple if statements? When should I use if statements with else if statements?


#1

Question

When should I use multiple if statements? When should I use if statements with else if statements?

Answer

We can use multiple if statements when we want to check multiple conditions no matter if the previous if statement was true/false. With multiple if statements, each statement will be checked even when a previous statement evaluates to true.

We want to use if statements along with else if statements when we want to check multiple conditions based on the evaluation of the previous statement, the conditions will stop being checked when a statement evaluates to true.

Example:

let num = 40;

//using only `if` statements, each of the following conditions will be checked

//the following condition evaluates to `false`, the next condition will be checked
if(num < 10){
  //do something
}

//the following condition is the only on that evaluates to `true`, code inside this `if` block will execute
if(num >= 10 && num <= 50) {
  console.log('test')
}

//this condition will still be checked even though the previous condition was evaluated to `true`
if(num > 50) {
  //do a thing
}

vs.

let num = 40;

//using `if` and `else if` statements the code will stop checking conditions after one of the conditions is evaluated to `true`

//this first condition is checked, evaluates to `false`, the next condition will be checked
if(num < 40){
  //do something
}

//the previous condition was evaluated to `false` so the following condition will be checked, and it evaluates to `true` so code inside this `else if` block will execute
else if(num >= 10 && num <= 50) {
  //do something else
}

//the following condition will not be checked as the previous condition evaluated to `true`
else if(num > 50) {
  //do a thing
}