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? ...

Bash Proficiency

Bash Proficiency In Under 15 Minutes Bash Proficiency In Under 15 Minutes Cheat sheet and in-depth explanations located below main article contents… The UNIX shell program interprets user commands, which are… Bash Proficiency In Under 15 Minutes Cheat sheet and in-depth explanations located below main article contents… The UNIX shell program interprets user commands, which are either directly entered by the user, or which can be read from a file called the shell script or shell program. Shell scripts are interpreted, not compiled. The shell reads commands from the script line per line and searches for those commands on the system while a compiler converts a program into machine readable form, an executable file. LIFE SAVING PROTIP: A nice thing to do is to add on the first line #!/bin/bash -x I will go deeper into the explanations behind some of these examples at the bottom of this article. Here’s some previous articles I’ve written for more advanced users. Bash Commands That Sa...