52

I want to use return false to break a .each() but also return a value at the same time. How can I do this?

Please refer to a work-around function to see what I am trying to do:

function HasStores(state) {
    var statehasstores = false;

    $(stores).each(function (index, store) {
        if (state == store.state && store.category == "meyers") {
            statehasstores = true;
            return false;  // break
        }
    });

    return statehasstores;
}

What Id like to do in pseudo code is:

Function () {
    for() {
        if found {
            return true;
        }   
    }
    return false;
}
2
  • It is already doing that! Look my example jsfiddle.net/aXkcW
    – BrunoLM
    Oct 15, 2010 at 23:09
  • This is the first in SO that I found the answer I was looking for inside the question OP asked lol
    – NecipAllef
    Nov 12, 2016 at 8:37

8 Answers 8

44

You're doing it right...

Quote from http://api.jquery.com/each/

"We can stop the loop from within the callback function by returning false."

4
  • 10
    That doesn't answer the question. He also wants to return a value after returning false, i.e. distinguish return false from simply terminating the loop.
    – Ariel
    Jun 26, 2016 at 23:57
  • @Ariel How about jsbin.com/tonozu/edit?html,js,console ? The return value is true if the condition is met (just like OP’s pseudo-code mandates), and it breaks out of the loop. Jun 27, 2016 at 0:08
  • @ŠimeVidas That (the JS, not JQ, some method) is completely irrelevant. I'm amazed this answer has 36 (!) upvotes and remains the accepted answer (because the OP can change that). Please see my answer. Aug 26, 2017 at 18:49
  • @mikerodent I don’t understand your answer. From what I see, OP needs a function that checks if a jQuery collection contains an element with a given state value. Aug 27, 2017 at 5:55
16

Be creative:

try {
  $(stores).each(function (index, store) {
    if(state == store.state && store.category == "meyers"){
      throw store;
    }
  });
}
catch(e) {
  // you got e with the value
}

No, I was just kidding, don't use this :). It came as an idea I liked to share.

2
  • 5
    I feel really bad upvoting this ... but I really like the creative thought ^^
    – Levite
    Sep 23, 2015 at 8:39
  • I can't remember what the "orthodox" view currently is in JS regarding the use of Exceptions as routine code techniques. The "gurus" of some languages at certain times have dabbled with this idea... but for me, being a simpleton, I tend to think "Exceptions for exceptional situations", or "When code takes exception to something, throw an Exception". The one, um, exception to this might be when alternatives are just too complex. But that isn't the case here. One practical reason for avoiding this sort of use of Exceptions is that you don't know the overheads involved in processing them. Aug 26, 2017 at 19:11
14

Use a variable outside the loop to get the value and use it afterward.

var value;

$(stores).each(function (index, store) {
    if(state == store.state && store.category == "meyers"){
        statehasstores = true;
        value = store; // added line
        return false; //break
    }
});

alert(value);

The way you're doing is just fine. I've tested on jsFiddle, see an example here.

It's not working for you? Can you show more context?

5

Alternatively, you could use a for loop instead of each(), and just return the value.

0
2

What you're suggesting is the way to do it. I'd think of it less as a workaround and more as an idiom.

2

How about:

$.each( myObj, function( key, value ){
  ...
  if( sthg... ){
    myObj.somethingWentHorriblyWrong = true;
    return false;
  }
});

if( myObj.somethingWentHorriblyWrong ){
  // ... do something, not forgetting to go:
  delete myObj.somethingWentHorriblyWrong;
}

PS I was initially interested in what $.each(... actually returns. As it says on the relevant JQ page, "The method returns its first argument, the object that was iterated", but in fact the solution doesn't even require that you use that fact...

PPS Need a function that returns a value? Wrap in an outer function of course.

1

Okay I guess there's a little doubt about this point so maybe I'm making it clearer here :

  • When jquery doc says : "We can stop the loop from within the callback function by returning false." and you do :

    Function () { for() { if found { return true; }
    } return false; }

This doesn't mean that you're function will return true when find the searched element. Instead, it will always return false.

So to make your function work as you whish I propose to do so :

Function () {
   variable found = false;
foreach() {
    if found {
        found = true;
        return false; // This statement doesn't make your function return false but just cut the loop
    }   
}
return found;

}

Of course there are many other ways to perform this but I think this is the simplest one.

Coopa - Easy !

0

As others have noted from jQuery Each, returning false will only break from the loop not return the value, returning true however will 'continue' and immediately begin the next iteration. With that knowledge, you could somewhat simplify your code like this:

function HasStores(state) {
  var statehasstores = false;

  $(stores).each(function (index, store){

    // continue or break;
    statehasstores = !(state == store.state && store.category == "meyers"))
    return statehasstores;
  });

  return !statehasstores;
}

This of course is a little silly using the double negative, and has the side effect of saving 'true' to statehasstores for every false iteration and vice versa, however the end result should be the same and you no longer have that if statement.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.