DEV Community

Discussion on: If/else or just if?

Collapse
 
farble1670 profile image
Jeffrey Blattman • Edited

I prefer the "return early" syntax. It puts a line in the code where if you pass it, you know some assertion holds. The code above doesn't really illustrate that, but for example:

if (flag1) {
  return;
}
// Anything that follows, regardless of if / else nesting
// I know that flag1 is false.

As opposed to:

if (flag1) {
  return;
} else {
  // some stuff
}
// Some more stuff. Is flag1 false?

In the second example, imagine some ugly nesting. For each block of code you need to think "am I in a level where I've tested flag1?"

Collapse
 
tyrw profile image
Tyler Warnock

@farble1670 so do you prefer a hybrid of first and second? Something like:

if (typeof val === 'string') {
    return 'A'
}
if (val === null || val === undefined) {
    return 'B'
}
return val