Get the Most Out of Your Break
var i=0; myLoop: for(i=0; i<10; i++) if(i == 5) break myLoop; alert(i);
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!
Jeffrey Gilbert - May 14, 2010