Do I need the last `else` clause in the if ... else if statement?

Every example if...else ifI saw includes a final sentence else:

if (condition1) {
  doA();
} else if (condition2) {
  doB();
} else if (condition3) {
  doC();
} else {
  noConditionsMet();
}
alwaysDoThis();

I understand that this is basically syntactic sugar for nested statements if...else:

if (condition1) {
  doA();
} else {
  if (condition2) {
    doB();
  } else {
    if (condition3) {
      doC();
    } else {
      noConditionsMet();
    }
  }
}
alwaysDoThis();

I have never seen examples if...else ifthat omit the last sentenceelse . But, seeing that simple expressions if(without sentences else) are valid, and by going over the equivalent "nested operators" above, my gut tells me that this is normal:

if (condition1) {
  doA();
} else if (condition2) {
  doB();
} else if (condition3) {
  doC();
}
alwaysDoThis();

Can someone point me to a resource or an example that clearly indicates whether it is valid?

And on another level, if that is true, would it be recommended or considered "bad practice"?

+10
4

else . , , , .

else , . , else , , , , "" . , else, , , , condition1, condition2 condition3 .

else , if , if if/else if, else if . JavaScript, , .

+5

else. ( -, , .)

, , - .

+9

100%. , . , .

, , :

function doStuff(data) {
    if (data.something) {
        // go format the data in some way
    }
    else if (data.somethingElse) {
        // go format the data in some other way
    }
    // must be formatted correctly, don't do anything else
    ...
}
+7

else, , else, if. else, elseif .

: . stackoverflow:

+1

Source: https://habr.com/ru/post/1648841/


All Articles