4

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?

Community
  • 1
  • 1
Brad
  • 159,648
  • 54
  • 349
  • 530
  • 1
    A console is not part of the language. How the console decides to represent something has no impact on what that thing actually is. –  Apr 21 '12 at 00:52
  • @amnotiam, I realize that, which is why my question is whether or not the console output I was seeing was due to the the console's formatting, or the way the object was actually stored. Dennis has answered that question. – Brad Apr 21 '12 at 01:34

2 Answers2

5

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.

Dennis
  • 32,200
  • 11
  • 64
  • 79
  • +1 i'd like to know more. do you have any references as to why it returns an array-like structure instead of an object? are `length` and `splice` the only things needed to create an array-like array-like structure? – Joseph Apr 21 '12 at 00:35
  • 1
    The structure is really no different internally, the console just displays it differently. [Search for isArray](http://fbug.googlecode.com/svn/lite/branches/firebug1.4/build/firebug-lite-debug.js) to see the qualifications for Array-like as far as the console is concerned. That is Firebug code but to my knowledge Chrome uses the same criteria. – Dennis Apr 21 '12 at 00:46
2

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.

  • Nice tool! I will definitely be downloading it. And, thanks for your answer and reference to the unit test as well. – Brad Apr 21 '12 at 05:18