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