Gotchas of Array.fill method in JavaScript

In one of our previous blog posts, we used Array.fill to create a pre-populated array. You can check out the post here

Today, we are going to see the pitfall of using Array.fill for the pre-populated array.

Array.fill works well when you are pre-populating a primitive datatype value. (i.e., string, integer, boolean, etc.,). For example,

const authorNames = new Array(3).fill('Param');
authorNames[2] = 'Joshua';
console.log(authorNames); // ["Param", "Param", "Joshua"]

But it won't work the same way for object data. Let's see it in example,

const authors = new Array(2).fill({});
authors[0].name = 'Param';
console.log(authors); // [{ name: "Param" }, { name: "Param" }]

As you see, both the object have the same name even though we only add name to the first value of the array.

Because Array.fill fills the value by reference. So if you change one value, then it will change for all the values.

In short, primitive datatypes fill by value. And the objects fill by reference. So next time, when you use the Array.fill method, use it with caution.