How to break/exit from an each() function in JQuery?
Break out of a $.each()
loop in jQuery by using return false;
within the callback function:
This code halts the loop when value
is equivalent to "stopValue"
.
Principle of breaking in jQuery's each()
For those fond of sneak peeks, using return false;
in jQuery's each()
function is similar to a break
in traditional JavaScript loops. Your escape hatch out of the iteration.
Effective iteration control is essential, letting you manage the loop conditionally:
- With
return false;
, exit the loop immediately when your condition satisfies. - Use
return true;
or an unadornedreturn;
to skip the current step and continue the loop, because why the rush, right?
Practical cases for controlling iteration flow
Looking for a needle in a haystack
Working only on a subset of elements
Error handling within the loop
Dealing with layer-cake loops (nested ones!)
Nested loops are common when dealing with multi-dimensional datasets. And yes, nested cakes taste the best! Exiting a nested .each()
is also done using return false;
:
Bear in mind that return false;
will only break the innermost loop. If you wish to bail out from an outer loop, you'll need some additional planning.
Gotchas and common tripwires
Gotcha #1: Misplacement of return false;
can cause unexpected exits. Position it judiciously within your condition sections.
Gotcha #2: Not all each-like functions in different JavaScript libraries humour return false;
the same way. Check the documentation for consistent behaviour.
Tripwire: Some developers mistake return false;
for event.preventDefault();
. The former is a loop flow controller in jQuery's .each()
, while the latter is specific to events.
Was this article helpful?