Possible Duplicate:
Are Javascript arrays sparse?
I am learning JavaScript at the moment and have been reading some simple introductions and tutorials. While looking at the Array object I stumbled upon some details, which strike me as very odd, coming from other languages like C/Java/Scala/…
So lets assume we define an array as such:
var arr = ['foo','bar','qux']
We now assign
arr[5] = 'baz'
which results in our array looking like this:
arr
>> ["foo", "bar", "qux", undefined, undefined, "baz"]
And the length is as expected
arr.length
>> 6
JavaScript has kindly expanded our array to the needed length – six – and the new items are set to undefined – except for the one we actually assigned a value to.
From a low level point of view this is horrible memory-wise. Typically an array would be a continuous range in memory – making an array bigger generally involves copying the whole array to a new memory location, sufficient in size. This is a very costly operation.
Now, I do realize that this is likely not what JavaScript engines are doing, as copying around arrays would be crazy expensive and the memory space would be wasted on all these ‘undefined’ values.
Can someone tell me what actually happens behind the door?
- Are arrays actually some sort linked lists?
- Are the ‘undefined’ array items actually there?
- How expensive is it to work with large arrays that are mostly filled with ‘undefined’?
In the first version of JavaScript, there were no arrays. They were later introduced as a sub-class of that “mother of all objects”:
Object. You can test this quite easily by doing this:This will log
String, time and time again. Internally, all numeric keys are converted to strings. The Length property merely fetches the highest index, and adds 1 to it. Nothing more. When you display your array, the object is iterated, and for each key, the same rules apply as for any object: first the instance is scanned, then the prototype(s)… so if we alter our code a bit:You’ll notice the array only has 5 own properties, the
undefinedkeys 4-8 are undefined, because there was no corresponding value found within the instance, nor in any of the underlying prototypes. In short: Arrays aren’t really arrays, but objects that behave similarly.As Tim remarked, you can have an array instance with an undefined property that does exist within that object:
But again, there is a difference:
RECAP, your three main questions:
Arrays are objects, that allow you to reference their properties with numeric instances
The
undefinedvalues are not there, they’re merely the default return value when JS scans an object and the prototypes and can’t find what you’re looking for: “Sorry, what you ask me is undefined in my book.” is what it says.Update:
Just quoting the Ecma std: