Course contentsShow
← JavaScript
Lesson 893 of 2,72320. Array Iteration and TransformationFree lesson

Fill Gotcha: Reference vs Primitive Values

Understand why fill() with objects creates shared references, not separate copies across indices.

Fill Gotcha: Reference vs Primitive Values

What you'll learn: Why using fill() with objects can create unexpected shared state across all filled array positions.

The Core Problem

When you use fill() with primitive values (numbers, strings, booleans), each array position gets its own independent copy. But when you fill an array with an object, JavaScript doesn't create separate copies—it places the same reference to that one object in every position.

The Analogy

Imagine a classroom where every student needs a notebook. With primitives, it's like giving each student their own notebook—if one student writes something, it only appears in their notebook. With objects, it's like giving every student a key to the same shared notebook—when anyone writes in it, everyone sees the change because they're all using the same notebook!

The Code

// Primitives: Each position is independent
const numbers = new Array(3).fill(0);
numbers[0] = 10;
console.log(numbers); // [10, 0, 0] ✓ Only first changed

// Objects: All positions share the same reference!
const users = new Array(3).fill({ name: 'Guest' });
users[0].name = 'Alice';
console.log(users); 
// [{ name: 'Alice' }, { name: 'Alice' }, { name: 'Alice' }] ⚠️
// Changing one changed ALL because they're the same object!

The Solution

To create independent objects, use Array.from() with a mapping function instead:

const users = Array.from({ length: 3 }, () => ({ name: 'Guest' }));
users[0].name = 'Alice';
console.log(users);
// [{ name: 'Alice' }, { name: 'Guest' }, { name: 'Guest' }] ✓

Key Takeaway: fill() with objects creates shared references, not independent copies. Use Array.from() with a mapping function when you need separate object instances.