Search code examples
javascriptchain

How to stop writing chain code?


for example...

if ( /* Condition */ ) {

    if ( /* Condition */ ) {

        if ( /* Condition */ ) {

          // Superb!

        } else {

          // Error 3

        }

    } else {

      // Error 2

    }

} else {

  // Error 1

}

Do you know how to avoid this? Thank you!


Solution

  • If this is a library function, throw may be the appropriate action.

    if (!condition1) {
        throw "Condition 1 failed.";
    }
    
    if (!condition2) {
        throw "Condition 2 failed.";
    }
    
    if (!condition3) {
        throw "Condition 3 failed.";
    }
    
    // Superb!
    

    Other acceptable actions might be:

    • Returning 0, null, or undefined.
    • Displaying an error to the user and returning.

    You will have to determine which failure action is right for your use case.