0

When using a spread operator, a new object is created so:

const foo = { a: 1 }
const m1 = {...foo}
const m2 = {...foo}
m1 === m2 // false

However, when using Array.fill(), this is not the case:

const m3 = Array(2).fill({...foo})
m3[0] === m3[1] // true

I have tried this a few different ways but I always end up with .fill() passing by reference and not creating a new object. Any idea why this is happening?

Alternatives I have tried:

where foo creates a new object every time it is called. I've tried this both with spread and without

const foo = () => ({ a: 1 })
const m4 = Array(2).fill({...foo()}) 
m4[0] === m4[1] // true

where the array is defined before hand and spread operator is also used in .fill().

const m5 = Array(2)
m5.fill({...foo()})
m5[0] === m5[1] // true
Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153
nemo
  • 334
  • 1
  • 3
  • 10
  • [This question has already been answered here.](https://stackoverflow.com/questions/35578478/array-prototype-fill-with-object-passes-reference-and-not-new-instance) – nemo Feb 01 '18 at 21:59
  • 1
    also `Array.from({length:2}, _ => ({...foo}))` – Slai Feb 01 '18 at 22:12
  • 1
    In `Array(2).fill({...foo})`, a new object *is* created because of the object literal, just like in your first snippet. Then that single object is passed into `fill`. – Bergi Feb 02 '18 at 01:55

0 Answers0