javascriptstructureprogram-flow

What's the cleanest way to branch based on which conditional broke a while loop in Javascript?


Say I've got this loop

while(condition1 && condition2 && condition3 && condition4){
     browseReddit();
}

if (!condition1){}
if (!condition2){}
if (!condition3){}
if (!condition4){}

It could be broken by any of the 4 conditions becoming false, and I would want to execute different code based on which one(s) it was. Ideally, I would not like to evaluate them all more than I absolutely have to. Assume browseReddit() forces us to evaluate them all again.

Putting an if chain after the loop is how I'm doing it currently. Is there a cleaner way? value brevity above all else in your answer.


Solution

  • while (1) {
        stop = 0;
        if (!condition1) {
            // condition 1 code
            stop = 1;
        }
        if (!condition2) {
            // condition 2 code
            stop = 1;
        }
        if (!condition3) {
            // condition 3 code
            stop = 1;
        }
        if (!condition4) {
            // condition 4 code
            stop = 1;
        }
        if (stop) {
            break;
        }
        browseReddit();
    }