Early Returns/Exits - Code Patterns in JavaScript

Code Patterns in JavaScript

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

You could wrap your implementation in an if statement.

TypeScript
const onSubmit = (form) => {
  if (form.valid) {
    // Do something here
  }
};

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

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

  // Do something here
};

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.

TypeScript
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
};

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

LinkEarly 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.

TypeScript
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
};

LinkConclusion

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.

LinkReferences

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

Join our Newsletter and be the first to know when I launch a course, post a video or write an article.

This field is required
This field is required