1

Some of the common things asked is , why Array appears to be zero even if there's content inside. My question now is a bit weird. Why am I seeing

 (66) [empty × 65, {…}]

in chrome console even if the array has at least 1 array value inside ?

sasori
  • 5,249
  • 16
  • 86
  • 138

2 Answers2

2

That is what you see when you have a sparse array - with some indicies defined, but some indicies lower than the defined indicies not defined (or ever assigned to), for example:

const arr = [];
arr[65] = 'foo';
console.log(arr);

(look at the results of these two snippets in the browser console, snippet console won't be visible)

Note that this is different from having literal undefined values in the first 65 indicies, which will be shown as undefined rather than empty:

const arr = new Array(65).fill(undefined);
arr[65] = 'foo';
console.log(arr);

Sparse arrays are almost never a good idea, though - if you ever see this, it's an indication that you should probably fix the code to avoid the sparse arrays. Consider another structure instead, perhaps an object with numeric keys:

const obj = {
  '65': 'foo'
};

A programmer will expect an array to be an ordered collection of elements - what would it mean for a collection to not have any value at all at the top of an ordered collection (not just undefined, but not any value)? It just doesn't make much sense - while possible, such constructs are not what arrays are for.

As Kaiido notes, empty elements will not be iterated over with array methods like forEach:

const arr = [];
arr[65] = 'foo';
arr.forEach((item, i) => {
  console.log(item, i);
});

Which makes a bit of sense, but it's still unintuitive (would you have been sure of this without trying the code yourself or looking up the spec?). One would usually expect the first iteration of a forEach callback to have an index of 0.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • Can you give more info or examples on why gaps are a bad idea? – Zim84 Jan 18 '19 at 07:08
  • @Zim84 They're odd and unintuitive, as you can see by the existence of this question. A programmer will expect an array to be an ordered collection of elements - what would it mean for a collection to not have any value at all at the top of an ordered collection (not just `undefined`, but not any value)? It just doesn't make much sense - while *possible*, such constructs are not what arrays are for. – CertainPerformance Jan 18 '19 at 07:13
  • @Kaiido I did note "look at the above in the browser console, not the snippet console" :) – CertainPerformance Jan 18 '19 at 07:19
1

It's just 65 empty elements, it's can be if you create array like this:

const arr = Array(65);
arr.push(1);
console.log(arr)

or in new Array set new element on some index;

const arr = [];
arr[65] = 1;
Vadim Hulevich
  • 1,803
  • 8
  • 17