How to break out of .each() and return a value for a function

JavascriptJquery

Javascript Problem Overview


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;
}

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

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.

Solution 3 - Javascript

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?

Solution 4 - Javascript

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

Solution 5 - Javascript

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

Solution 6 - Javascript

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.

Solution 7 - Javascript

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 !

Solution 8 - Javascript

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionParoXView Question on Stackoverflow
Solution 1 - JavascriptŠime VidasView Answer on Stackoverflow
Solution 2 - JavascriptmhitzaView Answer on Stackoverflow
Solution 3 - JavascriptBrunoLMView Answer on Stackoverflow
Solution 4 - JavascriptMark BesseyView Answer on Stackoverflow
Solution 5 - JavascriptKoobzView Answer on Stackoverflow
Solution 6 - Javascriptmike rodentView Answer on Stackoverflow
Solution 7 - JavascriptelkolotfiView Answer on Stackoverflow
Solution 8 - JavascriptOne_Dead_HeadphoneView Answer on Stackoverflow