1

Can somebody explain please how this code works under the hood:

let arr = Array(3).fill({}) // [{}, {}, {}]
arr[0].hi = "hi"            // [{ hi: "hi" }, { hi: "hi" }, { hi: "hi" }]

Why does this reference all elements? And how would I reference only the first one?

Markus Waas
  • 148
  • 6

1 Answers1

2

You are filling each position in the array with the same reference of an object, it is the same as

let a = {};
const b = a;
a.hi = 'hi';
console.log(b);
Adrian Brand
  • 20,384
  • 4
  • 39
  • 60