TIL #3: Early Returns/Guard Clauses in JavaScript (and React)

TIL #3: Early Returns/Guard Clauses in JavaScript (and React)

Early Return

Early Return is a pattern that suggests we avoid nested if-else statements by checking the preconditions and return or throw as early as possible. Usually, Early Return is also called Gaurd Clause or Bouncer Pattern.

Contrived Example

// Before
function doSomething(user, data) {
  if (hasPermission(user)) {
    if (isNetworkAvailable()) {
      if (isValid(data)) {
        sendToServer(user, data);
      } else {
        throw new DataInvalidError();
      }
    } else {
      saveInQueue(user, data);
    }
  } else {
    throw new PermissionDeniedError();
  }
}

to

function doSomething(user, data) {
  if (!hasPermission(user)) {
    throw new PermissionDeniedError();
  }

  if (!isNetworkAvailable()) {
    saveInQueue(user, data);
    return;
  }

  if (!isValid(data)) {
    throw new DataInvalidError();
  }

  sendToServer(user, data);
}

It's helpful

  1. in keeping our code readable and understandable
  2. as it offloads the burden in our mind when dealing with complex conditions

Reference link: javascript.plainenglish.io/early-return-wit..