I'm trying to understand the difference between an 'empty' sparse array (e.g. new Array(3)
) and an equivalent 'empty' dense array (array with 3 undefined entries).
I can create an array with 3 undefined values these two ways:
var sparse = new Array(3);
// or
var sparse = [,,,];
var dense = Array.apply(null, Array(3)); // See dense array link below
If I do console.log for either of these the result is:
[undefined, undefined, undefined]
If I loop over each array to compare it against the other one they will strictly match:
console.log(sparse.length === dense.length);
// true
for (var i = 0; i < dense.length; i++) {
console.log(i +':'+ (dense[i] === sparse[i]));
}
// '0:true'
// '1:true'
// '2:true'
However, if I use .forEach
(or map
, reduce
, etc) then the callback will never be called on the sparse array but will be called three times on the dense one:
sparse.forEach(function(val,i){
console.log(i +':'+ val);
});
// Nothing. No-op.
dense.forEach(function(val,i){
console.log(i +':'+ val);
});
// '0:undefined'
// '1:undefined'
// '2:undefined'
So my questions are:
- If they both have the same length, indexes, and values how is one iterable but the other isn't?
- What is the reason for the difference?
- What is the best way to determine if an array is sparse or dense?