1

I'm struggling with a weird Array.prototype.fill behaviour:

const arr = new Array(5)
   .fill([]);
arr[0].push('element pushed to 0 only');
console.log(arr[1]); // ['element pushed to 0 only']

All of the items inside the array are filled with this string. I assume all of the [] array-s are pointing to the same array, but I don't see why, could anyone explain?

Adam Nagy
  • 77
  • 10

1 Answers1

2

In fill([]), the argument [] is evaluated before the call to fill.

It's the same as

const subarray = [];
const arr = new Array(5);
arr.fill(subarray);

which is the same as

const subarray = [];
const arr = new Array(5);
for (var i=0; i<arr.length; i++) arr[i] = subarray;

In other words you have the same sub array at all indices: arr[1] is arr[0].

If you want to have different subarrays, you coul do

const arr = Array.from({length:5}, ()=>[]);
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758