DEV Community

Lucas Paganini
Lucas Paganini

Posted on • Originally published at lucaspaganini.com

Early Returns/Exits - Code Patterns in JavaScript

Code Patterns in JavaScript

See this and many other articles at lucaspaganini.com

Suppose you have a function that should only run if a given condition is true.

You could wrap your implementation in an if statement.

const onSubmit = (form) => {
  if (form.valid) {
    // Do something here
  }
};
Enter fullscreen mode Exit fullscreen mode

But a clearer approach is to use an early return if the condition is false.

const onSubmit = (form) => {
  if (form.valid === false) {
    return;
  }

  // Do something here
};
Enter fullscreen mode Exit fullscreen mode

See, instead of running if the condition is true, you can invert the logic and refuse to run if the condition is false.

Those if statements are called guards because they prevent your code to run. And you can have as many guards as you want.

const onSubmit = (form) => {
  if (form.valid === false) {
    return;
  }

  const userData = form.value;
  if (isValidUser(userData) === false) {
    return;
  }

  if (emailIsTaken(userData.email)) {
    return;
  }

  // Do something here
};
Enter fullscreen mode Exit fullscreen mode

That avoids unnecessary layers of nesting and makes it very clear to anyone reading your code what are the requirements for it to run.

Early Exits

This pattern is called “early returns”, but I don’t really like that naming because it seems to only apply to return statements and that’s not what this is about.

A better name for it is “early exits”, after all, you can exit your code in other ways.

For example, if you’re not expecting those conditions to be false, you can throw instead of returning.

const onSubmit = (form) => {
  if (form.valid === false) {
    throw Error('Form is invalid');
  }

  const userData = form.value;
  if (isValidUser(userData) === false) {
    throw Error('Invalid user data');
  }

  if (emailIsTaken(userData.email)) {
    throw Error('Email is already taken');
  }

  // Do something here
};
Enter fullscreen mode Exit fullscreen mode

Conclusion

References are in the references.

If you enjoyed the content, you know what to do. We have many other short and informative articles on our site. Subscribe if you’re interested in that.

Have a great day and see you soon.

References

  1. Replace Nested Conditional with Guard Clauses by Martin Fowler
  2. Refactoring - Improving the Design of Existing Code by Martin Fowler, with Kent Beck

Top comments (0)