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?
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.
Just for fun, let me add:
switch (true){
case iter.data === data: return iter;
case iter.data > data: iter = iter.left; break;
case iter.data < data: iter = iter.right; break;
}
With the example, I probably would do this though:
if (iter.data === data) {
return iter;
}
iter = (iter.data > data) ? iter.left : iter.right;
It highlights the different behavior between the branches (return vs assignment), which for me is the most important thing to recognize. And it even has the least lines of code.
But yes, it is a matter of taste.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With