Short answer:
return won't work this way in $.each. return will just exit the foreach loop.
var myDiv = $( "div" ).each(function( index, element ) {
return "xyz";
});
console.log(myDiv);
This will output undefined. Let's try different things and compare outputs:
Long answer
I'm agree that is not clear enough in the Jquery docs, they just say: "You can stop the loop from within the callback function by returning false." What about returning a variable, or returning true? Let's compare different functions:
var stores = ["C", "B", "A"];
function HasC() {
$(stores).each(function (i, s){
if(s=="C")
//yes, we have a C, so let's return true
return true;
});
}
function HasB() {
var b = false;
$(stores).each(function (i, s){
if(s=="B"){
b=true;
return b;
}
});
}
function HasA() {
var a = false;
$(stores).each(function (i, s){
if(s=="A"){
a = true;
return false;
}
});
return a;
}
HasC() will return undefined after but will iterate all the elements, without break
HasB will return undefined as well, because the b variable context is just inside the each function.
HasA() will return true and work as expected because once we found the "A", we stop the loop using return false and then after the loop we still have var a alive.