DEV Community

Discussion on: If/else or just if?

Collapse
 
qm3ster profile image
Mihail Malo • Edited

If we know the branches will have return, then B, plain if, aka early return is better.

We don't need to keep the context of whose else we are in anymore most of the time.

Even refactoring it is easier, both in terms of just editing the code and the resulting git diff.

However, if we don't have return...

let val
// ...
if (typeof val === 'string') {
    val = 'A'
} else if (val === null || val === undefined) {
    val = 'B'
} else {
    val = /* do something here lol */ val
}
// ...
use(val)

...then there are two options for me.

1. Extract into function

function testVal(val){
  if (typeof val === 'string') return 'A'
  if (val == null) return 'B'
  return val
}
// elsewhere...
let val
// ...
val = testVal(val)
// ...
use(val)

2. Use a conditional expression

let val
// ...
val =   
  typeof val === 'string'
  ? 'A'
  : val == null
    ? 'B'
    : val
// ...
use(val)

It just depends on the complexity, relevance, and size

What's particularly good about both?
They end up only assigning val once, so after some further refactoring we may end up with the superior const binding!

F.A.Q:

Is early return at odds with functional programming?
Should we strive to use conditional expressions at every size?

No. Used correctly, return is just guards in a match expression. You could see it as advanced pattern matching that is missing from JS syntax.
(Early throw, on the other hand, is usually a hack we have to use for lack of static types.)