Get the Most Out of Your Break

A rarely seen animal in the javascript world is a break. When it is seen 99% of the time it is within a switch statement. But did you know it can be used for more than that? In Javascript you can label your blocks of code, then when you call your break specify which block to break. Here's a simple example:

var i=0;

myLoop: for(i=0; i<10; i++)
        if(i == 5)
            break myLoop;


This code isn't rocket science but you will notice when i gets to 5 the loop is broken. The magic comes in when you have nest loops and you want to break out of a specific loop. That uses the same concept. Here's an example:

var i, k, magic=17;

myLoop: for(i=0; i<10; i++)
    myOtherLoop: for(k=0; k<10; k++)
        if((i+k) == magic)
            break myLoop;

alert(i +' + '+ k +' = '+ magic);

Try not to let the complex logic get in the way of the example ;) , but here you can see the break actually specifies "myLoop" which is the outer most in this case. Ok, your turn to try and break some stuff!