0

Which of the following constructions is proper, ex.1:

    if(condition1){
       //instruction to follow
} else if (condition2){
       //instruction to follow
} else if (condition3) {
       //instruction to follow
} else {

  return;
}

or ex.2:

      if(condition1){
           //instruction to follow
    } else if (condition2){
       //instruction to follow
    } else if (condition3){
       //instruction to follow
    }

The actual question is whether "if...else if" condition structure always needs to ends with "else" (ex.1) even if there is no such logical requirement or sometimes it can be free from that(ex.2)

Zebra
  • 189
  • 4
  • 13
  • 12
    No. It does not. – ken4z Mar 31 '17 at 19:46
  • 1
    You are never *required* to use an `else` (as you've probably discovered from testing the code)—just apply common sense and use `else` where it's helpful in your code flow. – Aurora0001 Mar 31 '17 at 19:46
  • No, they don't have to end with an `else`. If you want to get technical, there's no such thing as an `else if`. It's just taking advantage of the fact that `else { if (condition) { ... } }` can be written as `else if (condition) { ... }` since there's only one statement in the body of the `else`. But, yeah, the short answer is you never have to include an `else` at any time. Just use it if it makes sense. – Mike Cluck Mar 31 '17 at 19:46
  • depends on your requirement – Yogesh Mistry Mar 31 '17 at 19:47
  • I personally try to write as few else (or else if's) as possible. I think it reads better most of the time. You don't always need an else, but you'll find that you use them a lot. It all depends on your goals. If you're returning stuff in the if and else if's, and the else just returns, or returns null or something, then there's no need for sure. – adprocas Mar 31 '17 at 19:48
  • It don't have to: `function isEqualTest( $p ) { if( $p == 'test' ) { return true; } return false; }` - If you returning something from inside the true `if` condition then you don't need to have the else – Alon Eitan Mar 31 '17 at 19:49
  • 2
    https://developer.mozilla.org/it/docs/Web/JavaScript/Reference/Statements/if...else – Paolo Mar 31 '17 at 19:51

0 Answers0