How can I set a default return with if/else if/else statements like I do with the default case in a switch statement?


#1

Question

How can I set a default return with if/else if/else statements like I do with the default case in a switch statement?

Answer

We can set a default condition when using if/else if/else statements, like we do with the default case in a switch statement, by simply using an else statement after the rest of our if and else if conditions.

Example:

let x = 2;

if (x >= 10){
  //do something
} else if (x <= 1){
  //do something else
} else {
  console.log(`x is ${x}`);
}

The else statement acts as a catch-all for when our if or else if statements do not evaluate to true.