Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Array.prototype.fill() with object passes reference and not new instance in JavaScript?
When using Array.prototype.fill() with objects, JavaScript passes the same reference to all array positions instead of creating new instances. This means modifying one object affects all elements.
The Problem with fill() and Objects
Using fill() with an object creates multiple references to the same object:
// This creates the same object reference in all positions
let arr = new Array(3).fill({name: "John", age: 25});
console.log("Original array:");
console.log(arr);
// Modifying one element affects all
arr[0].name = "Alice";
console.log("After modifying arr[0].name:");
console.log(arr);
Original array:
[ { name: 'John', age: 25 }, { name: 'John', age: 25 }, { name: 'John', age: 25 } ]
After modifying arr[0].name:
[ { name: 'Alice', age: 25 }, { name: 'Alice', age: 25 }, { name: 'Alice', age: 25 } ]
Solution: Using map() with Object Constructor
To create separate object instances, use fill() followed by map():
// Creates separate empty objects
let arrayOfObjects = new Array(5).fill().map(Object);
console.log("Array of separate objects:");
console.log(arrayOfObjects);
// Modifying one doesn't affect others
arrayOfObjects[0].name = "Alice";
arrayOfObjects[1].name = "Bob";
console.log("After modifications:");
console.log(arrayOfObjects);
Array of separate objects:
[ {}, {}, {}, {}, {} ]
After modifications:
[ { name: 'Alice' }, { name: 'Bob' }, {}, {}, {} ]
Alternative: Using Array.from()
Another approach is using Array.from() with a mapping function:
// Using Array.from() to create separate objects
let arrayFromMethod = Array.from({length: 4}, () => ({value: 0}));
console.log("Using Array.from():");
console.log(arrayFromMethod);
// Each object is independent
arrayFromMethod[0].value = 10;
arrayFromMethod[1].value = 20;
console.log("After setting values:");
console.log(arrayFromMethod);
Using Array.from():
[ { value: 0 }, { value: 0 }, { value: 0 }, { value: 0 } ]
After setting values:
[ { value: 10 }, { value: 20 }, { value: 0 }, { value: 0 } ]
Comparison
| Method | Creates Separate Objects? | Performance |
|---|---|---|
new Array(n).fill({}) |
No ? same reference | Fast but problematic |
new Array(n).fill().map(Object) |
Yes | Good |
Array.from({length: n}, () => ({})) |
Yes | Good |
Conclusion
Use new Array(size).fill().map(Object) or Array.from() to create arrays of separate object instances. Avoid fill() directly with objects to prevent shared references.
Advertisements
