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 ?
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 ?
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.
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;