How Lodash _.fill Mutates an Existing Array

The _.fill method in the Lodash JavaScript library mutates an existing array by replacing its elements with a specified value across a designated range of indices. Unlike non-destructive array methods that return a new copy, _.fill directly alters the original array in place and returns a reference to that same array. This article explores the exact mechanics of this mutation, its parameters, return behaviors, and the common pitfalls related to shared object references.

In-Place Modification

When you invoke _.fill(array, value), Lodash does not allocate memory for a new array. Instead, it iterates over the provided array and overwrites the existing elements with the specified value.

const numbers = [1, 2, 3, 4, 5];
_.fill(numbers, 0);

console.log(numbers); 
// Output: [0, 0, 0, 0, 0]

Because the mutation occurs in place, any variable or constant referencing the original array will reflect the changes immediately.

Return Value Identical to Target

The method returns the mutated array itself. Consequently, the returned reference is strictly equal (===) to the input array:

const original = ['a', 'b', 'c'];
const result = _.fill(original, '*');

console.log(result === original); 
// Output: true

Specifying Index Ranges

The method accepts optional start and end parameters: _.fill(array, value, [start=0], [end=array.length]).

const items = [10, 20, 30, 40, 50];
_.fill(items, '*', 1, 4);

console.log(items); 
// Output: [10, '*', '*', '*', 50]

Elements outside the specified range remain entirely unchanged.

The Object Reference Trap

When passing an object, array, or function as the fill value, Lodash fills each slot with a reference to that single object in memory rather than creating independent clones.

const grid = [{}, {}, {}];
_.fill(grid, { active: false });

// Mutating one element
grid[0].active = true;

console.log(grid);
// Output: [{ active: true }, { active: true }, { active: true }]

Because all indices point to the exact same reference, modifying a property on one element inadvertently modifies it for all filled positions.

Parity with Native JavaScript

Lodash's _.fill behaves identically to the native ECMAScript 2015 Array.prototype.fill() method. While useful in legacy codebases or pipelines utilizing Lodash chaining, modern JavaScript applications can achieve identical in-place mutation natively via array.fill(value, start, end).