Quick Tip: Labeled ifs

I was pondering over label use cases in JavaScript the other day — how and when they should be used. Now the obvious case includes loops and stopping them given the right condition:

var i = 0;  
theAnswerToTheUniverse: while ( true ) {  
    console.log( ++i );
    if ( i === 42 ) break theAnswerToTheUniverse;
}

But what intrigued me was the definition of break on the MOZILLA DEVELOPER NETWORK (MDN):

Break — Terminates the current loop, switch, or label statement and transfers program control to the statement following the terminated statement.

...label statement... Now that is interesting. This gives JavaScript developers the possibility to break out of not just loops and switch statement, but also any other statement which can be labeled — For example: if statements. Check out the following code:

myTest: if ( condition ) {  
    // some code...
    if ( anotherCondition ) break myTest;
    // more code if anotherCondition is falsy...
}

The same code could of course be written as follows:

if ( condition ) {  
    // some code...

    if ( !anotherCondition ) {
        // more code if anotherCondition is falsy...
    }
}

Which one to use? Well it depends on the project but now you at least know about the possibility of using labeled ifs.