Question

My question is the same as Are Javascript arrays sparse? with one difference...

Are JavaScript arrays sparse, as implemented in Node.js (and/or V8)? I had assumed the were, but then I did the following test:

var testArray = [];
testArray[10000] = 'test';
console.log(testArray);

Returned is 10,000 blank elements, with 'test' at the end. Is this because of the way the debugging output works, or does Node.js actually allocate memory for the undefined array elements when adding new elements?

Was it helpful?

Solution

Node's util.inspect function specifically checks for sparse arrays to print them like that. In fact, it has a test that specifically checks for it. I know this because my full rewrite of node's inspector ultimately didn't make it into core, and lead to my UltraREPL.

OTHER TIPS

What you are seeing is not an actual array, just a representation. The console checks for the presence of a length and a splice property and prints the numeric properties of the object, which is why jQuery collections appear to be arrays when logged.

function RandomThingThatIsDefinitelyNotAnArray() {
    this.splice = function() {};
    this.length = 10;
    this[5] = 5;
}

console.log(new RandomThingThatIsDefinitelyNotAnArray());​
// shows [undefined, undefined, undefined, undefined, undefined, 5]

jsfFiddle for a live demo.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top