Breaking out of a PrototypeJS .each() loop

Mark Biek picture Mark Biek · Jun 25, 2009 · Viewed 11.3k times · Source

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?

Answer

Matthew Flaschen picture Matthew Flaschen · Jun 25, 2009
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.