Back to blog

Don't pass an object into Javascript's Array.fill()



You create an array with 5 empty values:

const array = new Array(5)

You then fill it with object literals:

array.fill({}, 0, 5) // [{},{},{},{},{}]

You then try to update only the first object

array[0].foo = "bar"

But you accidentally mutated all 5 objects! Not just the first object.

[




{foo:"bar"},



{foo:"bar"},



{foo:"bar"},



{foo:"bar"},



{foo:"bar"}



]

Each element of the array held a reference to the same empty object.

We mutated the object in memory to now be {foo:"bar"} . The 5 elements in the array still point to that object which is now {foo:"bar"}.

So each value in the array now evaluates to {"foo":"bar"}.

The solution

If you want each element of the array to hold references to different objects, then use this instead:

const array = Array.from({ length: 5 },()=>({}))




array[0].foo = "bar"



// [{"foo":"bar"},{},{},{},{}]

You can use a similar approach when dealing with arrays rather than objects:

const array = Array.from({ length: 5 },()=>([]))




array[0].push("foo")



// [["foo"],[],[],[],[]]


Sam is a software engineer from Sydney. See his portfolio here. You can read more of Sam's blogs here Feel free to get in touch here

Don't pass an object into Javascript's Array.fill()





You create an array with 5 empty values:

const array = new Array(5)

You then fill it with object literals:

array.fill({}, 0, 5) // [{},{},{},{},{}]

You then try to update only the first object

array[0].foo = "bar"

But you accidentally mutated all 5 objects! Not just the first object.

[




{foo:"bar"},



{foo:"bar"},



{foo:"bar"},



{foo:"bar"},



{foo:"bar"}



]

Each element of the array held a reference to the same empty object.

We mutated the object in memory to now be {foo:"bar"} . The 5 elements in the array still point to that object which is now {foo:"bar"}.

So each value in the array now evaluates to {"foo":"bar"}.

The solution

If you want each element of the array to hold references to different objects, then use this instead:

const array = Array.from({ length: 5 },()=>({}))




array[0].foo = "bar"



// [{"foo":"bar"},{},{},{},{}]

You can use a similar approach when dealing with arrays rather than objects:

const array = Array.from({ length: 5 },()=>([]))




array[0].push("foo")



// [["foo"],[],[],[],[]]

Back