Does JavaScript populate empty array items?
arrays, javascript, memory-management
Solution
When you set the value of a numeric index higher than the current `length` of your array, the `length` property is affected.
In brief, you should use an `Object`:
var data = {};
data[year] = "some data";
// or
var data = {
2009: "2009 data",
2010: "2010 data"
};
Now I answer the question title: "Does JavaScript populate empty array items?"
No, as I said before, only the `length` property is changed, (if necessary, only if the index added is larger than the current `length`), `length` is incremented to be one more than the numeric value of that index.
The `Array.prototype` methods work assuming that the array object will have its indexes starting from zero.
The previous indexes don't really exist in the `Array` object, you can test it:
var array = [];
array[10] = undefined;
array.hasOwnProperty(10); // true
array.hasOwnProperty(9); // false
In conclusion, arrays are meant to contain sequential indexes, starting from zero, if your properties don't meet those requirements, you should simply use an object.
Problem
I am coding a lot of annual data in JavaScript, and I was considering adding it to arrays, using the year as the array index and putting the data into the array. However, Firebug seems to be indicating that JavaScript handles this by populating two thousand odd entries in the array with "undefined." With hundreds of such arrays kicking around in active memory, I'm worried the overhead of hundreds of thousands of useless array items could start to slow the program down. Will it?