1

I have found that these two different methods of creating an array of arrays produce different behaviors:

// Method 1
for (var arr1 = []; arr.push([]) < len;) {}

// Method 2
var arr2 = new Array(len).fill([])

The arrays created look the same in the console, however they behave differently in my code. What could be causing this?

BBales
  • 6,588
  • 3
  • 16
  • 19

2 Answers2

3

The difference is that in the 1st method each index points to a different array, while in the Array#fill all indexes point to the same array.

Note: the 1st method will not create an array of arrays

var len = 3;
var arr1 = [];

// Method 1
for (var arr1 = []; arr1.push([]) < len;) {} // new sub array is pushed into arr1

// Method 2
var arr2 = new Array(len).fill([]) // each place in the array is filled with a reference to the same array 

arr1[0].push(1); // push to the 1st element of arr1
arr2[0].push(1); // push to the 1st element of arr2

console.log('arr1: ', JSON.stringify(arr1)); // only the 1st sub array contains 1
console.log('arr2: ', JSON.stringify(arr2)); // all sub arrays contain 1
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
  • Interesting. I did some googling, and found this: https://chrisrng.svbtle.com/es6-array-prototype-fill – VKK Jan 09 '17 at 19:53
1

Update: While the answer below is technically accurate, and is another difference between the two methods, @Ori Drori's answer is almost certainly what the OP is looking for.

I'll take a stab at this, but more context would be helpful.

In common practice, these two statements typically behave the same, but there is a key difference - when you use the new keyword, the Javascript interpreter calls the Array constructor.

If you were to overwrite the Array constructor, this would only apply to arr2 which was defined with the new keyword. arr1 created with the array literal would still be a Javascript array.

As an example, let's say I wrote the following code:

function Array() {
}

Method 1 would still work, but Method 2 would return a TypeError indicating that fill is not a function.

Interestingly, using the Array literal (Method 1) still calls the Array constructor, so if I did a console.log("test"); within the Array construction this would still be printed to the console when using either method. BUT, when the Array literal (Method 1) is used, the object itself still remains a standard Javascript array even if the Array constructor is overwritten.

VKK
  • 882
  • 7
  • 19