Skip to main content

improve-nested-conditionals

How can we improve and make a more efficient nested if statement in javascript?

if (color) {
    if (color === 'black') {
        printBlackBackground();
    } else if (color === 'red') {
        printRedBackground();
    } else if (color === 'blue') {
        printBlueBackground();
    } else if (color === 'green') {
        printGreenBackground();
    } else {
        printYellowBackground();
    }
}

One way to improve the nested if statement would be using the switch statement. Although it is less verbose and is more ordered, it’s not recommended to use it because it’s so difficult to debug errors. Here’s why.

switch (color) {
    case 'black':
        printBlackBackground();
        break;
    case 'red':
        printRedBackground();
        break;
    case 'blue':
        printBlueBackground();
        break;
    case 'green':
        printGreenBackground();
        break;
    default:
        printYellowBackground();
}

But what if we have a conditional with several checks in each statement? In this case, if we want it less verbose and more ordered, we can use the conditional switch. If we pass true as a parameter to the switch statement, it allows us to put a conditional in each case.

switch (true) {
    case typeof color === 'string' && color === 'black':
        printBlackBackground();
        break;
    case typeof color === 'string' && color === 'red':
        printRedBackground();
        break;
    case typeof color === 'string' && color === 'blue':
        printBlueBackground();
        break;
    case typeof color === 'string' && color === 'green':
        printGreenBackground();
        break;
    case typeof color === 'string' && color === 'yellow':
        printYellowBackground();
        break;
}

If refactoring is an option, we can try to simplify the functions themselves. For example instead of having a function for each background color we could have an function that takes the color as an argument.

function printBackground(color) {
    if (!color || typeof color !== 'string') {
        return; // Invalid color, return immediately
    }
}

But if refactoring is not an option, we must always avoid having several checks in every condition and avoid using switch as much as possible. We also must take into account that the most efficient way to do this is through an object.

var colorObj = {
    black: printBlackBackground,
    red: printRedBackground,
    blue: printBlueBackground,
    green: printGreenBackground,
    yellow: printYellowBackground
};

if (color in colorObj) {
    colorObj[color]();
}

Here you can find more information about this.

Comments

Popular posts from this blog

Breaking Down Scope, Context, And Closure In JavaScript In Simple Terms.

Breaking Down Scope, Context, And Closure In JavaScript In Simple Terms. Breaking Down Scope, Context, And Closure In JavaScript In Simple Terms. “JavaScript’s global scope is like a public toilet. You can’t avoid going in there, but try to limit your contact with surfaces when you… Breaking Down Scope, Context, And Closure In JavaScript In Simple Terms. Photo by Florian Olivo on  Unsplash “ J avaScript’s global scope is like a public toilet. You can’t avoid going in there, but try to limit your contact with surfaces when you do.” ― Dmitry Baranowski Here’s another (much) more simple article I wrote on the subject: Closures In Javascript Answer A closure is a function defined...

links

links Absolutely Everything You Could Need To Know About How JavaScript TOC & Condensed Links **** **** **** **** **** 1 2 3 4 5 leonardomso/33-js-concepts *This repository was created with the intention of helping developers master their concepts in JavaScript. It is not a…*github.com Call stack - MDN Web Docs Glossary: Definitions of Web-related terms MDN *A call stack is a mechanism for an interpreter (like the JavaScript interpreter in a web browser) to keep track of its…*developer.mozilla.org Understanding Javascript Function Executions — Call Stack, Event Loop , Tasks & more *Web developers or Front end engineers, as that’s what we like to be called, nowadays do everything right from acting as…*medium.com Understanding the JavaScript call stack *The JavaScript engine (which is found in a hosting environment like the browser), is a single-threaded interpreter…*medium.freecodecamp.org Javascript: What Is The Execution Context? ...

React Tricks

REACT-TIPS React Tips Replace Redux with React Query As our application gets larger it becomes harder to manage state across our components, we may reach for a state management library like Redux. If our application relies on data that we get from an API, we often use Redux to fetch that server state and then update our application state. This can be a challenging process; not only do you have to fetch data, but you also need to handle the different states, depending on whether you have the data or are in a loading or error state. Instead of using Redux to manage data you get from a server, use a library like React Query. React Query not only gives you greater control over making HTTP requests in your React apps through helpful hooks and the ability to easily refetch data, but it also enables us to seamlessly manage state across our app components, of...