Skip to main content

Command Palette

Search for a command to run...

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

Published
1 min read
TIL #3: Early Returns/Guard Clauses in JavaScript (and React)
N

I am a self taught web developer owning experience of 12+ years in web development field.

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: https://javascript.plainenglish.io/early-return-with-react-hooks-f96fa4a33124

L

Thanks for the information, https://shellshockers.app I will try to figure it out for more. Keep sharing such informative post keep suggesting such post.

O
Otis Jame3y ago

Early Returns/Guard Clauses in JavaScript https://amongus2.io (and React). Agenda In this article, we will go through the following sections: The basic concept of Early Return.

K
Kane Lani3y ago

I am very impressed with your articles, your content is very engaging and easy to understand. I have read many other websites but I still like your site. moviedle quordle

W

Worth reading post. Thanks for the wonderful post. - dissertation help service uk

F
felicia124y ago

amazing, this essay has a fascinating subject. Slope game is a fun game in which you try to get as near as possible to a moving ball while running at top speed. You can play it by yourself or with your friends. In no time, your heart will be racing and your adrenaline will be pumping.

R

it is really helpful. thank you for sharing