Have you ever run into a situation where you tried to fill an array with objects, only to realize that modifying one object also affected all the other objects in the array? This often happens when using the `fill` method on an array containing objects. In this article, we will delve into why this occurs and how you can work around it when dealing with object references and instances in JavaScript.
When you fill an array with objects using the `fill` method, you are actually filling it with references to the same object, not creating new instances of the object for each array element. This means that if you modify the properties of one object in the array, all other array elements referencing the same object will reflect those changes as well.
Let's take a look at a simple example to illustrate this behavior:
const obj = { name: 'Alice', age: 30 };
const arr = new Array(3).fill(obj);
obj.age = 31;
console.log(arr);
In this example, we fill an array with three references to the `obj` object. When we later update the `age` property of the `obj` object, all elements in the `arr` array will reflect this change because they all reference the same object.
To avoid this issue and ensure that each array element contains a unique instance of the object, you can use the `map` method along with `Object.assign` or the spread operator. Here's how you can achieve this:
const obj = { name: 'Bob', age: 25 };
const arr = new Array(3).fill(null).map(() => ({ ...obj }));
obj.age = 26;
console.log(arr);
By using the `map` method along with the spread operator (`{ ...obj }`), we create a new object instance for each element in the array. This way, modifying one object will not affect the others since they are now separate instances.
Another approach is to use `Object.assign` to achieve the same result:
const obj = { name: 'Charlie', age: 20 };
const arr = new Array(3).fill(null).map(() => Object.assign({}, obj));
obj.age = 21;
console.log(arr);
In this example, `Object.assign({}, obj)` creates a new object by copying the properties of the original `obj` object. This ensures that each element in the array references a distinct object.
In conclusion, when filling an array with objects in JavaScript, be aware that the `fill` method assigns references to the same object by default. To avoid unintended side effects from object mutation, use the `map` method in conjunction with `Object.assign` or the spread operator to create new instances for each array element. This way, you can maintain separate copies of objects within the array and prevent unwanted shared references.