I’m trying to understand the right way to return values in jquery from a function. I’ve checked the API as well as other questions here and I can’t find the correct way to do this. All I want is a simple variable to be returned so I can set it as a global variable. Here’s what I got:
var a = 0, b, c;
var imgArr = [];
$(document).ready(function() { //populates array with images
var smooth = popArr();
alert(smooth);
}
function popArr(){
$("#thumb_slider").children().each(function(index, element) {
var newImg = $("<img />").attr({
src: this.src,
alt: 'space'
}).addClass(index == 0 ? "left_slot" : (index == 1 ? "middle_slot" : "right_slot"));
imgArr.push(newImg);
return imgArr; // This comes back as undefined.
});
}
My question is why is it returning undefined? Am I even supposed to use “return” in Jquery?
You try to return something from the
.eachcallback. The only useful return value of this function isfalseto cancel the “loop” early.Simply move your return statement after the
});and everything should work fine.You can also avoid the global variable – you return the array so there’s no need to make it global: