Call break in nested if statements

I have the following situation:

IF condition THEN  
    IF condition THEN 
        sequence 1
    ELSE
        break //?  
    ENDIF    
ELSE    
    sequence 3    
ENDIF

What is the result of the break statement? Does it break the outer if statement? Because this is what I actually need.


Solution 1:

If you label the if statement you can use break.

breakme: if (condition) {
    // Do stuff

    if (condition2){
        // do stuff
    } else {
       break breakme;
    }

    // Do more stuff
}

You can even label and break plain blocks.

breakme: {
    // Do stuff

    if (condition){
        // do stuff
    } else {
       break breakme;
    }

    // Do more stuff
}

It's not a commonly used pattern though, so might confuse people and possibly won't be optimised by compliers. It might be better to use a function and return, or better arrange the conditions.

( function() {
   // Do stuff

   if ( condition1 ) {
       // Do stuff 
   } else {
       return;
   }

   // Do other stuff
}() );

Solution 2:

no it doesnt. break is for loops, not ifs.

nested if statements are just terrible. If you can avoid them, avoid them. Can you rewrite your code to be something like

if (c1 && c2) {
    //sequence 1
} else if (c3 && c2) {
   // sequence 3
}

that way you don't need any control logic to 'break out' of the loop.

Solution 3:

In the most languages, break does only cancel loops like for, while etc.

Solution 4:

But there is switch-case :)

switch (true) {
    case true:
        console.log("Yes, its ture :) Break from the switch-case");
        break;
    case false:
        console.log("Nope, but if the condition was set to false this would be used and then break");
        break;

    default:
        console.log("If all else fails");
        break;
}

Solution 5:

Javascript will throw an exception if you attempt to use a break; statement inside an if else. It is used mainly for loops. You can "break" out of an if else statement with a condition, which does not make sense to include a "break" statement.

JSFiddle