Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 660
Mark Biek Avatar asked Jun 25 '09 18:06

Mark Biek


People also ask

How do you break a forEach loop?

There is no way to stop or break a forEach() loop other than by throwing an exception. If you need such behavior, the forEach() method is the wrong tool.

How do you stop a loop in Javascript?

The break statement terminates the current loop, switch , or label statement and transfers program control to the statement following the terminated statement.

What is Unsyntactic break?

The “Unsyntactic break” error occurs when we try to use a break statement outside of a for loop, or inside of a function in the for loop.10-Oct-2021.


1 Answers

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.

like image 130
Matthew Flaschen Avatar answered Sep 28 '22 03:09

Matthew Flaschen