Breaking Out (of Nested For-Loops)

(Interview) Question

How do you break out of nested for-loops? Let's say you have:

for( var i = 0; i < 10; i++ ) {
     for( var j = 0; j < 15;j++ ) {
         if ( j === 2 ) {
             // break out of everything!
         }
     }
}

Answer

Labels! Who knew you could label for-loops?

a: for( var i = 0; i < 10; i++ ) {
    b: for( var j = 0; j < 15;j++ ) {
        if ( j === 2 ) {
            break a;
        }
    }
}
comments powered by Disqus