DEV Community

Discussion on: Early Returns in JavaScript

Collapse
 
alainvanhout profile image
Alain Van Hout • Edited

Using early returns can be beneficial or problematic depending on the way that it's used.

Problematic usage typically relates to having return statements in several places across a bundle of loops and conditionals. This makes it very hard to (easily) grasp the flow of the code.

The most beneficial usage that I know of, is checking of things at the very beginning of the method. For example, if you have to combine several sources of data but have to return a certain default value if a specific and easily/efficiently identified condition is met, than it makes sense to add an early return. This is particularly true for validation:

function doThings(input) {
  if (input === null) {
    return null;
  }

  // do the actual things that expect input to not be null
}

(note that this isn't meant as a guideline on null-handling. It's just an easy example)