5

When i use Array.fill to fill a multidimensional array, i get a weird behaviour when pushing to one of the arrays:

var arr = Array(2).fill([]);
arr[0].push(5);
console.log(arr); 
//=> prints [[5], [5]]
Youssef
  • 1,033
  • 8
  • 16
  • both given answers are great examples of why you should learn about objects and how they work. mozilla developer network would be a good start for learning about this. tbh you could even do this: `var a = {}; (function(x){a.foo="bar"})(a); console.log(a.foo)` – GottZ Dec 02 '16 at 12:38

2 Answers2

7

fill is essentially doing this:

var content = [];
for (var i = 0; i < 2; i += 1) {
  arr[i] = content;
}

So, your array will have a reference to the array you've passed to fill in each property.

user3297291
  • 22,592
  • 4
  • 29
  • 45
2

It sounds weird, but what your code actually does is create an array ([]) and put a reference for that array in each of the items of the Array(2). So whenever you change that reference - every array that is referenced to that Array is changed.

It's exactly the same as:

var a = [];
var arr = Array(2).fill(a);
a.push(5);
console.log(arr[0][0], arr[1][0]);
a[0] = 2;
console.log(arr[0][0], arr[1][0]);

You can see that the values inside the arr are affected by the change to the a array.

Dekel
  • 60,707
  • 10
  • 101
  • 129