Search code examples
javascriptprototypejs

Breaking out of a PrototypeJS .each() loop


In this very contrived example, I have an array with 3 elements that I'm looping over using the .each() method.

var vals = $w('foo bar baz'); 

vals.each( function(val) {
    alert(val);

    if( val == 'bar' ) {
        //This exits function(val)
        //but still continues with the .each()
        return;
    }
});

I can easily return out of the function being called by .each() if I need to.

My question is, how can I break out of the .each() loop from inside the function that .each() is calling?


Solution

  • if( val == 'bar' ) {
        throw $break;
    }
    

    It's documented at the same page you linked. It's an exception specially handled by the each function. When thrown, it prevents your function from being called on further elements.