views:

68

answers:

5

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  A: 

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

Koobz
+7  A: 

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."

Šime Vidas
+1  A: 

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

Mark Bessey
+2  A: 

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?

BrunoLM
+1  A: 

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.

mhitza
I like the idea. :P
BrunoLM