How to break out of jQuery each loop?
Asked Answered
B

8

854

How do I break out of a jQuery each loop?

I have tried:

 return false;

in the loop but this did not work. Any ideas?


Update 9/5/2020

I put the return false; in the wrong place. When I put it inside the loop everything worked.

Bullbat answered 23/11, 2009 at 17:44 Comment(7)
For posterity: why did the questioner say returning false did not work? Virtually every answer says to do that. Wondering if it was possibly because that only terminates the each-loop. A return statement inside a for-loop, by contrast, would exit the loop and the calling function. To get such drastic behavior from an each-loop, you'd need to set a flag with closure-scope inside the each-loop, then respond to the flag outside it.Appalachian
@BobStein-VisiBone Someone deleted my original comment. I put the return false in the wrong place. When I fixed it everything worked.Bullbat
not sure why the "update" says return false doesn't work with $().each - because it does.Aberdare
@Bullbat you should update the question to make it clear what was not working. This Q/A makes no sense when your question says the accepted answer does not work.Foley
@Bullbat can you please update this question. Still a relevant one all these years later, and a top Google result!Regolith
@Regolith How would you like the question changed? I'll edit it but not sure what will be appropriate.Bullbat
@Luke101, sorry to pick up an old thread, but for clarity, I'd suggest removing all but the first line. Thanks for asking the question : )Practicable
S
1507

To break a $.each or $(selector).each loop, you have to return false in the loop callback.

Returning true skips to the next iteration, equivalent to a continue in a normal loop.

$.each(array, function(key, value) { 
    if(value === "foo") {
        return false; // breaks
    }
});

// or

$(selector).each(function() {
  if (condition) {
    return false;
  }
});
Shredding answered 23/11, 2009 at 17:46 Comment(6)
Just what I was looking for, thanks. @OZZIE, just use "return true;" or "return false;" based on your conditions.Septum
What does @CMS mean with "return false in the loop callback."? Where exactly is this?Indehiscent
E.g. $.each(array, function(key, value) { if(value == "foo") return false; });Swor
Don't know jQuery had to swap parameter positions from the javascript forEach.Wunderlich
@AlexR Breaking out of a $().each is done in exactly the same way, your edit only serves to cause confusion.Vogler
@Jake, agree, will edit the answer to note you can use the same way for both.Tillich
S
62

According to the documentation return false; should do the job.

We can break the $.each() loop [..] by making the callback function return false.

Return false in the callback:

function callback(indexInArray, valueOfElement) {
  var booleanKeepGoing;

  this; // == valueOfElement (casted to Object)

  return booleanKeepGoing; // optional, unless false 
                           // and want to stop looping
}

BTW, continue works like this:

Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.

Shaneka answered 23/11, 2009 at 17:49 Comment(0)
L
41

I came across the situation where I met a condition that broke the loop, however the code after the .each() function still executed. I then set a flag to "true" with an immediate check for the flag after the .each() function to ensure the code that followed was not executed.

$('.groupName').each(function() {
    if($(this).text() == groupname){
        alert('This group already exists');
        breakOut = true;
        return false;
    }
});
if(breakOut) {
    breakOut = false;
    return false;
} 
Litmus answered 24/1, 2014 at 23:10 Comment(0)
H
38

I created a Fiddle for the answer to this question because the accepted answer is incorrect plus this is the first StackOverflow thread returned from Google regarding this question.

To break out of a $.each you must use return false;

Here is a Fiddle proving it:

http://jsfiddle.net/9XqRy/

Hilaire answered 8/11, 2013 at 1:15 Comment(1)
I like the fiddle, but I'm not sure why you say the accepted answer is incorrect, because you're both saying the same thing.Monophony
R
17

I know its quite an old question but I didn't see any answer, which clarify that why and when its possible to break with return.

I would like to explain it with 2 simple examples:

1. Example: In this case, we have a simple iteration and we want to break with return true, if we can find the three.

function canFindThree() {
    for(var i = 0; i < 5; i++) {
        if(i === 3) {
           return true;
        }
    }
}

if we call this function, it will simply return the true.

2. Example In this case, we want to iterate with jquery's each function, which takes anonymous function as parameter.

function canFindThree() {

    var result = false;

    $.each([1, 2, 3, 4, 5], function(key, value) { 
        if(value === 3) {
            result = true;
            return false; //This will only exit the anonymous function and stop the iteration immediatelly.
        }
    });

    return result; //This will exit the function with return true;
}
Retrochoir answered 22/8, 2018 at 14:4 Comment(0)
L
7

"each" uses callback function. Callback function execute irrespective of the calling function,so it is not possible to return to calling function from callback function.

use for loop if you have to stop the loop execution based on some condition and remain in to the same function.

Ludicrous answered 25/11, 2015 at 5:58 Comment(0)
P
6

I use this way (for example):

$(document).on('click', '#save', function () {
    var cont = true;
    $('.field').each(function () {
        if ($(this).val() === '') {
            alert('Please fill out all fields');
            cont = false;
            return false;
        }
    });
    if (cont === false) {
        return false;
    }
    /* commands block */
});

if cont isn't false runs commands block

Prior answered 29/6, 2020 at 6:1 Comment(0)
C
-1

> We can break the loop by using break keyword.

Example:

for (let i = 0; i < 10; i++) {
  if (i === 3) { break; }
  text += "The number is " + i + "<br>";
}
Carreon answered 16/2, 2024 at 9:6 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.