Unitialized variables in an array when using only Array.push?
<p>I've run into a rather interesting problem. The code below generates an array that, when logged, gives the value <code>[undefined × 1]</code>. According to <a href="http://stackoverflow.com/a/10683811/339852">this answer</a>, that means that the array has unitialized indexes--in this case, only one. However, since I'm only using <code>array.push()</code> to avoid exactly this sort of problem, I'm kind of lost. To the best of my knowledge only assigning an index at least one index greater than other initialized indexes could cause the problem. Anyhow, here's the code:</p>

<pre><code>function Thing(params) {
    var that = this;

    this.OtherObject = function OtherObject(param) {
        this.param = param;
    }

    this.Foo = function Foo() {
        this.bar = [];

        this.add = function(item) {
            if (this.bar.length != 0) {
                for (var i = 0, len = this.bar.length; i &lt; len; i++) {
                    if (this.bar[i].param &lt;= item.param) {
                        this.bar.splice(i, 0, item);
                    }
                }
            } else {
                this.bar[0] = item;
                console.log(this.bar);
            }
        }

        this.pop = function() {
            return this.bar.pop();
        }

        this.length = function() {
            return this.bar.length;
        }
    }

    this.someFunc = function() {
        var myThing = new that.Foo();
        myThing.add(new that.OtherObject(3));

        while (myThing.length() &gt; 0) {
            var someVar = myThing.pop();
        }
    }
}

var myThing = new Thing({
    myParam: "someValue"
});

myThing.someFunc();
​
</code></pre>

<p>I created a test case to see if I could narrow the problem down, but I ended up re-typing 95% of my code until I ran into the issue again, which appears to be related with my use of <code>myThing.pop()</code>. You can find a fiddle <a href="http://jsfiddle.net/cbYqG/3/" rel="nofollow">here</a> which demonstrates the issue in question. </p>

<p>So... any ideas as to what could be causing this? Is this actually a problem with the way I've nested my objects? (which I did following a pattern given to me in <a href="http://stackoverflow.com/a/10051156/339852">this answer</a> to a previous question of mine). </p>

<p>In case you're wondering what I could possibly be trying to do here, I'm treating the outside object like a sort of namespace, which I'm doing to avoid cluttering up the global namespace (this will eventually be a pathfinding library, if I get my act together here). The <code>Foo</code> object is meant to be a sort of ordered list such that I can get the closest node (the one with the lowest <code>param</code> property) by <code>pop()</code>ing the stack.</p>
