2

Consider the following example:

let A = new Array(3);
A.forEach((_, index) => {
  A[index] = 1;
});
console.log(A);

Why does it return [undefined undefined undefined]? I was expecting it to return [1 1 1].

ruohola
  • 21,987
  • 6
  • 62
  • 97
one-hand-octopus
  • 2,229
  • 1
  • 17
  • 51
  • Array methods only iterate over own-properties on the array. `new Array` results in an array without (array-indexed) own-properties. Try `A.hasOwnProperty(1)`, you'll see it gives you `false`. Since sparse arrays like these are really weird and unintuitive, best to never use `new Array` unless it's immediately followed by something that populates the whole array, like `.fill` – CertainPerformance Feb 07 '21 at 22:48

0 Answers0