skip to Main Content

So the code looks like as follows.

if () {
    do something;
}
else if () {
   do something;
}
.
.
. 
else if () {
    do something;
}
else {
    do something;
}

Does the else at the bottom only act if the else if above it is not satisfied or does it act if the beginning if statement is not satisfied?

2

Answers


  1. It will check the condition of each if/else if sequentially. When checks and sees that the condition is true then it will execute the code inside. If none of the above if/else if are true then it will execute whatever inside the else statement.

    For more information, see Javascript if else else if.

    I made a testing snippet for you to play with. You can choose number between 1 to 5 to see how the if/else if are working. After that, you should try any other input to see how the else is working.

    let input = parseInt(prompt("Choose number between 1 to 5"));
    if (input === 1){
      console.log('if 1');
    }
    else if (input === 2){
      console.log('else if 2');
    }
    else if (input === 3){
      console.log('else if 3');
    }
    else if (input === 4){
      console.log('else if 4');
    }
    else if (input === 5){
      console.log('else if 5');
    }
    else {
      console.log('else ' + input);
    }
    Login or Signup to reply.
  2. There are two different kinds of if..else constructs. The first is a simple if-else:

    if ( condition ) {
       console.log("Do stuff if condition is true");
    } else {
       console.log("Do stuff if condition is not true");
    }
    

    The next is an if-else-if:

    if ( condition ) {
       console.log("Do stuff if condition is true");
    } else if ( differentCondition ) {
       console.log("Do stuff if differentCondition is not true");
    } else {
       console.log("Do stuff if neither condition nor differentCondition is true");
    }
    

    You can also use else-if as many times as you like, e.g.:

    if ( condition ) {
       // do something
    } else if ( condition2 ) {
       // do something
    } else if ( condition3 ) {
       // do something
    } else if ( condition4 ) {
       // do something
    } else {
       // if nothing matches use this as a fallback
    }
    

    And every part of an if..else is optional, except for the initial if block. So if you don’t want to do anything if condition is not true, you can just omit the else block entirely:

    if ( condition ) {
       // do something if condition is true
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search