Search code examples
javascriptarraysnode.jssparse-array

Are JavaScript/ECMAScript arrays "sparse" in Node.js?


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?


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.