DEV Community

Discussion on: Ditching the "else" Statement

Collapse
 
haaxor1689 profile image
Maroš Beťko • Edited

I feel like you did not provide complex enough example to show of what a huge difference in code readability can early return make.

Let's say we have some complicated fetch that needs to first get some ticket and then use it in a 2nd request.

const fetchData = async (id?: string) => {
  if (id) {
    const ticketResponse = await fetch('api/ticket');
    if (ticketResponse.ok) {
      const response = await fetch (`api/data?t=${await ticketResponse.text()}`);
     if (response.ok) {
       return await response.json();
     } else {
       return 'Response fetch error';
     }
    } else {
      return 'Ticket fetch error';
    }
  } else {
    return 'No id';
  }
}
Enter fullscreen mode Exit fullscreen mode

Now this is a horrible code to read because for every if you need to look for corresponding else and you need to constantly jump between lines when trying to understand the code.

Why early return is so good is because with it, every time an error occurs that should end the function in earlier step, you can return from the function and not think about that branch of execution after.

const fetchData = async (id?: string) => {
  if (!id) {
    return 'No id';
  }

  const ticketResponse = await fetch('api/ticket');
  if (!ticketResponse.ok) {
    return 'Response fetch error';
  }

  const response = await fetch (`api/data?t=${await ticketResponse.text()}``);
  if (!response.ok)  {
    return 'Ticket fetch error';
  }

  return await response.json();
}
Enter fullscreen mode Exit fullscreen mode

And this is the main reason for early return.

  • No unnecessary indentation
  • When reading, you don't need to jump between lines to find the other execution branch
  • Any errors/cases that causes function to not execute all steps returns and you don't need to think about that case after that since it's handled