DEV Community

Cover image for Stop Using if..else
Hasan Zohdy
Hasan Zohdy

Posted on

Stop Using if..else

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

function firstValue(data) {
    if (Array.isArray(data)) {
        return data[0];
    } else if (typeof data === 'object') {
        return data[Object.keys(data)[0]];
    }
}
Enter fullscreen mode Exit fullscreen mode

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

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

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

    if (typeof data === 'object') {
        return data[Object.keys(data)[0]];
    }
}
Enter fullscreen mode Exit fullscreen mode

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

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]];
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

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

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]];
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

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

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
    });
  }
}
Enter fullscreen mode Exit fullscreen mode

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

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
  });
}
Enter fullscreen mode Exit fullscreen mode

Using Continue and Break statements

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

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];
}
Enter fullscreen mode Exit fullscreen mode

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

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];
}
Enter fullscreen mode Exit fullscreen mode

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

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];
}
Enter fullscreen mode Exit fullscreen mode

And a good example will be

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
    ];
}
Enter fullscreen mode Exit fullscreen mode

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

Join our community on Discord 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)

General Topics

Packages & Libraries

Top comments (0)