Stop Using if..else
Tags: ifelse, controlstructure, codestructure, cleancode
Published: 2023-04-04 15:24:09

---
title: Stop Using if..else
published: true
description: stop using if else statements in this scenario
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4j4jphrcl9ymb92xlh1v.png
tags: ifElse, controlStructure, codeStructure, cleanCode
---

## Why?

Well, let me first tell you what i mean by stop using `if..else` statement.

The `if..else` statement is a control structure that allows you to execute a block of code if a condition is true, and another block of code if the condition is false.

So what is wrong with that?

Totally fine code, but this could be good in some cases, but not in all cases.

## The if stopper

Assume we have a function that returns the first value of an array or object

```js
function firstValue(data) {
    if (Array.isArray(data)) {
        return data[0];
    } else if (typeof data === 'object') {
        return data[Object.keys(data)[0]];
    }
}
```

The function looks so good, but can we do better with this function?

For sure the answer is yes, let's see how.

```js
function firstValue(data) {
    if (Array.isArray(data)) {
        return data[0];
    }

    if (typeof data === 'object') {
        return data[Object.keys(data)[0]];
    }
}
```

The function looks the same, but it's not the same, the second function is better than the first one.

Here we get rid of the if else, just by returning a value from the `if` statement we no longer need to use the `else` statement.

This makes the code more readable, and more maintainable, the previous example was a little small, but what if the function is huge, it will be harder to see where the else statement starts and ends, espcially if you have a lot of nested if statements.

Let's see an example of if...else statement that each statement has nested if statements and for loops

```js
function firstValue(data) {
    if (Array.isArray(data)) {
        for (let i = 0; i < data.length; i++) {
            if (typeof data[i] === 'object') {
                return data[i];
            }
        }
    } else if (typeof data === 'object') {
        for (let i = 0; i < Object.keys(data).length; i++) {
            if (typeof data[Object.keys(data)[i]] === 'object') {
                return data[Object.keys(data)[i]];
            }
        }
    }
}
```

This is a bad example, but it's just to show you how bad it can be, and how hard it is to read.

Let's write an improved version of this function

```js
function firstValue(data) {
    if (Array.isArray(data)) {
        for (let i = 0; i < data.length; i++) {
            if (typeof data[i] === 'object') {
                return data[i];
            }
        }
    }

    if (typeof data === 'object') {
        for (let i = 0; i < Object.keys(data).length; i++) {
            if (typeof data[Object.keys(data)[i]] === 'object') {
                return data[Object.keys(data)[i]];
            }
        }
    }
}
```

Both separated, both readable and everyone is happy.

## Using Throw Errors

You can also stop the function using throw errors, let's see a bad example

```js
const largeNumbers = [];
const smallNumbers = [];

export function badNumbersManipulator(value) {
  if (typeof value !== "number") {
    throw new Error("Value must be a number");
  } else if (value > 100) {
    const doubledNumber = value * 2;
    const halvedNumber = value / 2;
    const poweredNumber = Math.pow(value, 2);

    largeNumbers.push({
      number: value,
      double: doubledNumber,
      halved: halvedNumber,
      powered: poweredNumber
    });
  } else {
    const halvedNumber = value / 2;
    const quarterNumber = value / 4;
    const tripledNumber = value * 3;

    smallNumbers.push({
      number: value,
      halved: halvedNumber,
      triple: tripledNumber,
      quarter: quarterNumber
    });
  }
}
```

Here in the above example, we have a function that takes a number and push it to an array, but if the number is greater than 100, it will push it to the `largeNumbers` array, and if it's less than 100, it will push it to the `smallNumbers` array.

You see there are three concatenated if statements and each one of them stops the function, we can do better

```js
const largeNumbers = [];
const smallNumbers = [];

export function goodNumbersManipulator(value) {
  if (typeof value !== "number") {
    throw new Error("Value must be a number"); // stop the function
  }

  if (value > 100) {
    const doubledNumber = value * 2;
    const halvedNumber = value / 2;
    const poweredNumber = Math.pow(value, 2);

    largeNumbers.push({
      number: value,
      double: doubledNumber,
      halved: halvedNumber,
      powered: poweredNumber
    });

    return;
  }

  const halvedNumber = value / 2;
  const quarterNumber = value / 4;
  const tripledNumber = value * 3;

  smallNumbers.push({
    number: value,
    halved: halvedNumber,
    triple: tripledNumber,
    quarter: quarterNumber
  });
}
```

## Using Continue and Break statements

You can also use `continue` and `break` statements to stop the loop, let's see an example

```js
function badCountEvenAndOdds(array) {
  const evenNumbers = [];
  const oddNumbers = [];

  for (const value of array) {
    if (value % 2 === 0) {
      evenNumbers.push(value);
    } else {
      oddNumbers.push(value);
    }
  }

  return [evenNumbers, oddNumbers];
}
```

Here we have a function that takes an array of numbers and returns an array of two arrays, the first array contains the even numbers, and the second array contains the odd numbers, the function adds the number to the proper array.

But let's make it better

```js
function goodCountEvenAndOdds(array) {
  const evenNumbers = [];
  const oddNumbers = [];

  for (const value of array) {
    if (value % 2 === 0) {
      evenNumbers.push(value);
      continue;
    }

    oddNumbers.push(value);
  }

  return [evenNumbers, oddNumbers];
}
```

Now the code is readable, imagine we have like 3 or 4 if statements, it will be hard to read, but now it's easy to read.

Another example of using `break` statement

A bad example will be

```js
function doubleThreeAndFour(array) {
  let foundThreeNumber = 0;
  let foundFourNumber = 0;

  for (const value of array) {
    if (value % 3 === 0) {
      foundThreeNumber = value;
      break;
    } else if (value % 4 === 0) {
      foundFourNumber = value;
      break;
    }
  }

  return [foundThreeNumber * 2, foundFourNumber * 2];
}
```

And a good example will be

```js
function doubledThreeAndFour(array) {
    let foundThreeNumber = 0;
    let foundFourNumber = 0;

    for (const value of array) {
        if (value % 3 === 0) {
            foundThreeNumber = value;
            break;
        }

        if (value % 4 === 0) {
            foundFourNumber = value;
            break;
        }
    }

    return [
        foundThreeNumber * 2,
        foundFourNumber * 2
    ];
}
```

## Conclusion

Writing clean and readable code very essential, specially if you're not working alone on a project, you may have a lot of developers working on the same project, and you don't want to make it hard for them to read your code.

## 😍 Join our community

Answer problem solving questions and get mentor to review your answer on [mentoor.io](mentoor.io)

Join our community on [Discord](https://discord.gg/pb2vmdfhGf) to get help and support (Node Js 2023 Channel).

## 📚 Bonus Content 📚

You may have a look at these articles, it will definitely boost your knowledge and productivity.

Courses (Articles)

- [Nodejs Course 2023: Typescript, Fastify And MongoDB](https://dev.to/hassanzohdy/nodejs-course-2023-introduction-to-nodejs-3n4e)
- [OOP In JS And TS From The Very Beginning](https://dev.to/hassanzohdy/jsts-oop-course-1-introduction-2ld)
- [ES6++: The Ultimate Guide to ES6 and Beyond](https://dev.to/hassanzohdy/es6-1-introduction-h3e)
- [React Js: Let"s Create File Manager With React Js and Node Js](https://dev.to/hassanzohdy/lets-create-a-file-manager-from-scratch-with-react-and-typescript-chapter-i-a-good-way-to-expand-your-experience-5g4k)

General Topics

- [Event Driven Architecture: A Practical Guide in Javascript](https://dev.to/hassanzohdy/event-driven-architecture-the-best-paradigm-that-i-love-to-work-with-in-javascript-and-node-js-1gnk)
- [Best Practices For Case Styles: Camel, Pascal, Snake, and Kebab Case In Node And Javascript](https://dev.to/hassanzohdy/best-practices-for-case-styles-camel-pascal-snake-and-kebab-case-in-node-and-javascript-55oi)
- [After 6 years of practicing MongoDB, Here are my thoughts on MongoDB vs MySQL
](https://dev.to/hassanzohdy/after-6-years-of-practicing-mongodb-here-are-my-thoughts-on-mongodb-vs-mysql-574b)

Packages & Libraries

- [Powerful File System manager for Nodejs](https://dev.to/hassanzohdy/powerful-file-system-manager-for-nodejs-1f5h)
- [Mongez Cache, a powerful storage manager for web applications](https://dev.to/hassanzohdy/mongez-cache-a-powerful-storage-manager-for-web-applications-5bel)
- [React Atom: A simple yet powerful React JS / React Native state management](https://dev.to/hassanzohdy/react-atom-a-simple-yet-powerful-react-js-react-native-state-management-age)
- [Collections: Your ultimate Javascript Arrays Manager](https://dev.to/hassanzohdy/collections-your-ultimate-javascript-array-handler-3o15)
- [Supportive Is: an elegant utility to check types of values in JavaScript](https://dev.to/hassanzohdy/supportive-is-an-elegant-utility-to-check-types-of-values-in-javascript-1b3e)
- [Localization: An agnostic i18n package to manage localization in your project](https://dev.to/hassanzohdy/mongez-localization-the-simplest-way-to-translate-your-website-regardless-your-favorite-framework-4gi3)