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?
Share
When you set the value of a numeric index higher than the current
lengthof your array, thelengthproperty is affected.In brief, you should use an
Object:Now I answer the question title: “Does JavaScript populate empty array items?“
No, as I said before, only the
lengthproperty is changed, (if necessary, only if the index added is larger than the currentlength),lengthis incremented to be one more than the numeric value of that index.The
Array.prototypemethods work assuming that the array object will have its indexes starting from zero.The previous indexes don’t really exist in the
Arrayobject, you can test it: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.