1

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?

Digital Brent
  • 1,275
  • 7
  • 19
  • 47

2 Answers2

7

You try to return something from the .each callback. The only useful return value of this function is false to 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:

function popArr() {
    var imgArr = [];
    $("#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;
}
ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
0

the method popArr() is not returning anything. instead, it is calling .each()

since it is a global variable, just pushing elements into it will be enough.

mindandmedia
  • 6,800
  • 1
  • 24
  • 33