How to break out of jQuery each loop?

To break a $.each or $(mySelector).each loop, you have to  return false  inside the each loop. Returning true skips to the next iteration, is equivalent to a continue in a normal loop.

Here is an example. Stop iteration and exit from the each loop if the array element equals 5:

var myNumbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
function BreakIfFive() {
    $.each(myNumbers, function (i, o) 
    {
        console.log(i);
        
        if (i == 5) {
            return false;
        }
    });
}
BreakIfFive();

 

jquery how to break each loop

Leave a Comment