1

When I console.log(Array(2)) I am able to find map prototype function. But when I use it, this returns an array of undefined.

let result = Array(2).map((o, i) => {
  return i;
});

console.log(result);

I know I can use fill() or spread operator on Array(2) before using the map() but I'm just wondering why I'm getting this behavior.

john
  • 265
  • 1
  • 2
  • 5
  • Many (most) Array methods do not act on elements that have never been set to any value, which is true of all elements of an array newly-constructed with the Array constructor. – Pointy Nov 23 '19 at 00:08
  • Note that, contrary to what the snippet console says, you're not actually getting `[undefined, undefined]` - rather, you're getting a (nearly) *empty object* with a `.length` of 2 – CertainPerformance Nov 23 '19 at 00:08
  • Use `Array.from({ length: 2 }, (_, i) => i)` instead. – Sebastian Simon Nov 23 '19 at 00:21

0 Answers0