45

Consider the following code:

    var sentences = [
        'Lorem ipsum dolor sit amet, consectetur adipiscing elit.',
        'Vivamus aliquet nisl quis velit ornare tempor.',
        'Cras sit amet neque ante, eu ultrices est.',
        'Integer id lectus id nunc venenatis gravida nec eget dolor.',
        'Suspendisse imperdiet turpis ut justo ultricies a aliquet tortor ultrices.'
    ];

    var words = ['ipsum', 'amet', 'elit'];

    $(sentences).each(function() {
        var s = this;
        alert(s);
        $(words).each(function(i) {
            if (s.indexOf(this) > -1)
            {
                alert('found ' + this);
                return false;
            }
        });
    });

The interesting part is the nested jQuery.each() loops. As per the documentation, returning false will break out of the loop (discontinuing execution of the loop - similar to a normal JavaScript break statement), and returning non-false will stop the current iteration and continue with the next iteration (similar to a normal JavaScript continue statement).

I can break or continue a jQuery.each() on its own, but with nested jQuery.each, I've found it difficult to break out of the parent loop from within the child loop. I could use a boolean value, and update it on every child iteration, but I was wondering if there was an easier way.

I've set up an example at jsFiddle if you'd like to mess around with it. Simply click the "Test" button to run the example shown above.

TLDR: Is there anything resembling a labeled continue or break within the context of jQuery?

Ryan Kinal
  • 17,414
  • 6
  • 46
  • 63

11 Answers11

93

There are a lot of answers here. And it's old, but this is for anyone coming here via google. In jQuery each function

return false; is like break.

just

return; is like continue

These will emulate the behavior of break and continue.

Thihara
  • 7,031
  • 2
  • 29
  • 56
23

You should do this without jQuery, it may not be as "pretty" but there's less going on and it's easier to do exactly what you want, like this:

var sentences = [
    'Lorem ipsum dolor sit amet, consectetur adipiscing elit.',
    'Vivamus aliquet nisl quis velit ornare tempor.',
    'Cras sit amet neque ante, eu ultrices est.',
    'Integer id lectus id nunc venenatis gravida nec eget dolor.',
    'Suspendisse imperdiet turpis ut justo ultricies a aliquet tortor ultrices.'
];

var words = ['ipsum', 'amet', 'elit'];

for(var s=0; s<sentences.length; s++) {
    alert(sentences[s]);
    for(var w=0; w<words.length; w++) {
        if(sentences[s].indexOf(words[w]) > -1) {
            alert('found ' + words[w]);
            return;
        }
    }
}

You can try it out here. I'm not sure if this is the exact behavior you're after, but now you're not in a closure inside a closure created by the double .each() and you can return or break whenever you want in this case.

Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
  • Very good point. Even with the more complicated use of jQuery DOM selectors that makes up my actual use-case, they can be iterated over normally. – Ryan Kinal Jul 16 '10 at 18:31
  • Normal JavaScript gets the check. Man, I love this language. – Ryan Kinal Jul 16 '10 at 20:03
  • 1
    this solution is impeccably correct, but it does not address the stated question. It does not explain how to break out of a chain of nested 'each' loops. thus -1 (sorry) – Legna Oct 28 '15 at 18:02
  • @Legna Yes it does... Nick says you can return (break from both loops) or break (break from inner loop) using this solution. – mhodges Apr 08 '16 at 21:58
14

As is stated in the jQuery documentation http://api.jquery.com/jQuery.each/

return true in jQuery.each is the same as a continue

return false is the same as a break

Serj Sagan
  • 28,927
  • 17
  • 154
  • 183
8

I've used a "breakout" pattern for this:

$(sentences).each(function() {
    var breakout;
    var s = this;
    alert(s);
    $(words).each(function(i) {
        if (s.indexOf(this) > -1)
        {
            alert('found ' + this);
            return breakout = false;
        }
    });
    return breakout;
});

This works nicely to any nesting depth. breakout is a simple flag. It will stay undefined unless and until you set it to false (as I do in my return statement as illustrated above). All you have to do is:

  1. declare it in your outermost closure: var breakout;
  2. add it to your return false statement(s): return breakout = false
  3. return breakout in your outer closure(s).

Not too inelegant, right? ...works for me anyway.

joneit
  • 621
  • 6
  • 4
  • this is really nice, it is a shame that all the other answers - which aside from the selected answer are just wrong have been upvoted. – bharal Oct 13 '18 at 17:23
8

There is no clean way to do this and like @Nick mentioned above it might just be easier to use the old school way of loops as then you can control this. But if you want to stick with what you got there is one way you could handle this. I'm sure I will get some heat for this one. But...

One way you could do what you want without an if statement is to raise an error and wrap your loop with a try/catch block:

try{
$(sentences).each(function() {
    var s = this;
    alert(s);
    $(words).each(function(i) {
        if (s.indexOf(this) > -1)
        {
            alert('found ' + this);
            throw "Exit Error";
        }
    });
});
}
catch (e)
{
    alert(e)
}

Ok, let the thrashing begin.

spinon
  • 10,760
  • 5
  • 41
  • 59
  • 7
    Wow. This may be a blatant misuse of try/catch, but it works. – Ryan Kinal Jul 16 '10 at 18:30
  • @Ryan yeah I know. It completely goes against what/how we are taught to do things. But I was just trying to propose a solution. – spinon Jul 16 '10 at 18:37
  • 1
    Glad to help then. Surprised not really any thrashing. Must be light today or my self acknowledgment of the not best practice approach. – spinon Jul 16 '10 at 19:05
  • Almost gave you the check on this one, but it felt too dirty :-D Seriously, though, clever solution. – Ryan Kinal Jul 16 '10 at 20:02
  • 1
    I like it too! This is exactly why we call it "throwing an exception" now instead of "raising an error". One need only change "Exit Error" to a more diplomatic "Exit condition encountered" or some such, and we have laundered the concept and made it politically correct. :) One might say (if one is given to spin doctoring) that the rule here is that one loops "except" when an exit condition is encountered, at which point one throws an exception. – BobRodes Oct 04 '12 at 15:34
8

The problem here is that while you can return false from within the .each callback, the .each function itself returns the jQuery object. So you have to return a false at both levels to stop the iteration of the loop. Also since there is not way to know if the inner .each found a match or not, we will have to use a shared variable using a closure that gets updated.

Each inner iteration of words refers to the same notFound variable, so we just need to update it when a match is found, and then return it. The outer closure already has a reference to it, so it can break out when needed.

$(sentences).each(function() {
    var s = this;
    var notFound = true;

    $(words).each(function() {
        return (notFound = (s.indexOf(this) == -1));
    });

    return notFound;
});

You can try your example here.

Anurag
  • 140,337
  • 36
  • 221
  • 257
3

Unfortunately no. The problem here is that the iteration happens inside functions, so they aren't like normal loops. The only way you can "break" out of a function is by returning or by throwing an exception. So yes, using a boolean flag seems to be the only reasonable way to "break" out of the outer "loop".

casablanca
  • 69,683
  • 7
  • 133
  • 150
3

return true not work

return false working

found = false;
query = "foo";

$('.items').each(function()
{
  if($(this).text() == query)
  {
    found = true;
    return false;
  }
});
misima
  • 421
  • 5
  • 17
2

Labeled Break

outerloop:
$(sentences).each(function() 
{
    $(words).each(function(i) 
    {
        break; /* breaks inner loop */
    } 
    $(words).each(function(i)  
    {
        break outerloop; /* breaks outer loop */
    }
}
capdragon
  • 14,565
  • 24
  • 107
  • 153
2

Confirm in API documentation http://api.jquery.com/jQuery.each/ say:

We can break the $.each() loop at a particular iteration by making the callback function return false. Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.

and this is my example http://jsfiddle.net/r6jqP/

(function($){
    $('#go').on('click',function(){
        var i=0,
            all=0;
        $('li').each(function(){
             all++;
             if($('#mytext').val()=='continue')return true;
             i++;
             if($('#mytext').val()==$(this).html()){
                 return false;
             }
        });
        alert('Iterazione : '+i+' to '+all);
    });
}(jQuery));
Leonardo Ciaccio
  • 2,846
  • 1
  • 15
  • 17
0

You can break the $.each() loop at a particular iteration by making the callback function return false.

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

Dan
  • 1,238
  • 2
  • 17
  • 32