Array.fill gives same object repeated. why? [duplicate]

.fill will insert the same exact object (same instance) on each segment of the array.
That’s why doing .fill(Math.random) will return an array filled with always the same number.

You can do this to obtain what you want:

new Array(4).fill().map(() => ({}));

To explain what’s happening under the hood in your question’s code, let’s convert this to ES5 code:

var arr = new Array(4);  // new Array(4)
var obj = new Object();  // *1: with this object instance
for(i = 0; i < 4; i++) { // .fill( *1 )
  arr[i] = obj;
}

As you can see, we are assigning the same object instance (obj) to each cell of the array instance.

This is the same principle of why:

const obj = {};
const a = obj;
const b = obj;

a.foo = true;

Makes a.foo === b.foo resolve to true.

Leave a Comment