Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does JavaScript populate empty array items?

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?

like image 410
futuraprime Avatar asked Jan 11 '10 04:01

futuraprime


2 Answers

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.

like image 183
Christian C. Salvadó Avatar answered Nov 18 '22 22:11

Christian C. Salvadó


Yes, most likely. You should consider using a JavaScript object instead:

var years = {2009: 'Good', 2010: 'Better'};
like image 32
Brian McKenna Avatar answered Nov 18 '22 23:11

Brian McKenna