0

Why does this happen? If you execute this code you will see what is printed in the comments. I had assumed that A1, A2 and A3 would all be the same things.

const A1 = Array(3).fill([]);
const A2 = [[], [], []];
const A3 = [];
for (let index = 0; index < 3; index++) {
    A3.push([]);
}
console.log(A1 == A2 || A1 == A3 || A2 == A3); // False

In fact, A1 in particular is doing really weird things as highlighted below.

A1[0].push(5);
console.log(A1); // [ [ 5 ], [ 5 ], [ 5 ] ]

A2[0].push(5);
console.log(A2); // [ [ 5 ], [], [] ]

A3[0].push(5);
console.log(A3); // [ [ 5 ], [], [] ]
  • Using `Array(3).fill([]);` will fill your array with references to the same single array in memory. Your other examples create 3 unique arrays in memory – Nick Parsons Jul 06 '21 at 10:37
  • 2
    That’s two independent questions: the first one is a duplicate of [Why doesn't equality check work with arrays](/q/30820611/4642212), the second one is a duplicate of [Array.prototype.fill() with object passes reference and not new instance](/q/35578478/4642212). – Sebastian Simon Jul 06 '21 at 10:41

3 Answers3

4

as described here

the fill method of Array fills the array (or a given range of indices in the array) with the same value

that means when you write the line Array(3).fill([]) it actually puts the same array created using [] in all the indices of the array, so editing the array in one place, affects all indices (since they all point to the same array [])

the boi
  • 56
  • 2
3

Its because every element in A1 is the same array

its like:

let a = [];
let A1 = [a,a,a];
let b0 = [], b1 = [], b2 = []
let A2 = [b0, b1, b2]

Edit:

when you change A1[0] you change a

Ofek
  • 1,065
  • 6
  • 19
2

When using Array.prototype.fill() :

if the first parameter is an object, each slot in the array will reference that object

So if we modify a slot, all the slots will have the same value because they refer to the same object.

Namysh
  • 3,717
  • 2
  • 9
  • 17