Home > Mobile >  if / else / else if statements, a matter of function or style?
if / else / else if statements, a matter of function or style?

Time:12-07

I am comparing data that can have only 3 possible results, less than, greater than, or equal to.

Hence the last statement could be an else or an else / if, and the block would behave the same:

  if(iter.data === data) {
    return iter;
  } else if(data < iter.data) {
    iter = iter.left;

  // else or else if will suffice here
  } else if(data > iter.data) {
    iter = iter.right;
  }

Is there any functional difference I am missing, or is this simply a matter of style?

Is there a good style reference, that covers this if it is only a matter of style?

CodePudding user response:

The compiler/interpreter won't care and will optimize these regardless, but from a mental load standpoint else if implies another comparison, whereas else implies a "fall-through" and most codebases will prefer the latter.

As an added bonus, the fall-through also ensures that one of the branches is always taken. Generally speaking, no branches being taken at all could potentially lead to much weirder bugs than the wrong branch being taken.

CodePudding user response:

Would something like this work? check for less and greater but returns the default if both fail.

//if/else
if(data < iter.data) {
    return iter.left;
}
if(data > iter.data) {
    return iter.right;
}
return iter;

DanDavis suggested ternary so maybe this?

//ternary example
return data < iter.data ? iter.left : (data > iter.data ? iter.right : iter);
  • Related