How to Break Out of a jQuery $.each Loop
To break out of a jQuery $.each() loop early, you must
explicitly return false inside the callback function.
Because $.each() relies on a callback function to handle
each iteration, standard loop control statements like break
will trigger a JavaScript syntax error. Returning false
terminates the entire loop immediately, while returning
true acts as a continue statement to skip to
the next iteration.
The Solution: Returning
false
When jQuery executes the callback in a $.each() loop, it
checks the return value of that callback. If the function returns
false, jQuery halts the execution and exits the loop
immediately.
Here is an example demonstrating how to stop iterating when a specific condition is met:
const numbers = [10, 20, 30, 40, 50];
$.each(numbers, function(index, value) {
if (value === 30) {
console.log('Target found: ' + value + '. Exiting loop.');
return false; // Breaks out of the $.each loop
}
console.log('Processing: ' + value);
});
// Output:
// Processing: 10
// Processing: 20
// Target found: 30. Exiting loop.Why Native break
Does Not Work
In standard JavaScript loops (like for,
while, or for...of), the break
statement instructs the JavaScript engine to exit the loop block.
However, $.each() is an abstraction where each iteration
executes a separate function scope.
Writing break; inside this callback function will cause
an Uncaught SyntaxError: Illegal break statement because a
break keyword cannot exist outside an actual loop
block.
Skipping an
Iteration (The Equivalent of continue)
If your goal is to skip the current iteration and move to the next
item without stopping the entire loop, return true or use a
standard return statement:
const items = ['apple', 'skip_me', 'banana', 'orange'];
$.each(items, function(index, item) {
if (item === 'skip_me') {
return true; // Continues to the next iteration
}
console.log(item);
});
// Output:
// apple
// banana
// orangeModern JavaScript Alternatives
If you are working in a modern environment and want to avoid
callback-based iteration control entirely, you can convert the
collection into an array and use the native for...of loop,
where the standard break statement works as expected:
const elements = $('div').toArray();
for (const el of elements) {
if (el.id === 'stop-here') {
break; // Standard JavaScript break
}
console.log(el);
}