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?
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.
The break statement terminates the current loop, switch , or label statement and transfers program control to the statement following the terminated statement.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With