Q:

Javascript Garbage Collection on a Returned Array

I'm sure that this is an easy question for JS experts out there. Unfortunately for me I'm not one of them.
I've got the following situation. I'm creating an array in function b that I populate with some new objects. I then return that array back to function a (which called function b).
When I iterate through the returned array, the contents are all undefined. Off the cuff I figure that the JS garbage collector is probably involved here. How would I go about fixing this?
Sincerely,
mj
function a()
{
    var x = b();

    for( var v in x ){
        //print out v.id and v.name
    }
}

function b()
{
    var y = new Array();
    var m = new Object();
    var n = new Object();
    m.id = 1;
    n.id = 2;
    m.name = "alpha";
    n.name = "bravo";

    y.push( m );
    y.push( n );

    return y;
}

A:

The problem is how you are "iterating" through your array. You are using the for-in statement, and this statement should be used to enumerate object properties, not to iterate over arrays or array-like objects.
From your code:
for( var v in x ){
    //print out v.id and v.name
}

The for-in statement in every iteration will feed v with the name of each property, since you are using an array in your example, v will be '0', '1', etc.
You could access x[v] but I really encourage you to use a sequential for loop, for example:
for (var i = 0; i < x.length; i++) {
  alert(x[i].id);
  alert(x[i].name);
}

There are many reasons why to avoid for-in, when your purpose is "iterate" over numeric indexes on array like objects, see the following questions for more information:

Loop through array in JavaScript
JavaScript “For …in” with Arrays

