How copyWithin and fill Mutate JavaScript Arrays

JavaScript provides two specialized in-place array methods, Array.prototype.copyWithin() and Array.prototype.fill(), designed for high-performance data manipulation without altering array length. Both methods are destructive, meaning they directly modify the contents of the original array rather than returning a new array instance. This article explains how each method mutates array elements, breaks down their parameter mechanics, and provides practical code examples demonstrating their behavior.

The fill() Method

The fill() method replaces elements in an array with a specified static value. It mutates the target array directly and returns a reference to that modified array.

Syntax

array.fill(value, start, end)

How fill() Mutates Data

fill() iterates from the start index up to, but not including, the end index, assigning the provided value to each slot.

const numbers = [1, 2, 3, 4, 5];

// Fill the entire array with 0
numbers.fill(0);
console.log(numbers); // Output: [0, 0, 0, 0, 0]

const letters = ['a', 'b', 'c', 'd', 'e'];

// Fill with 'z' starting at index 1 up to index 4
letters.fill('z', 1, 4);
console.log(letters); // Output: ['a', 'z', 'z', 'z', 'e']

Negative indices count backward from the end of the array. For example, start = -2 begins filling two positions from the end.

The copyWithin() Method

The copyWithin() method performs a shallow copy of a sequence of elements from one section of an array to another position within the same array. It overwrites the existing elements at the target location without altering the overall length of the array.

Syntax

array.copyWithin(target, start, end)

How copyWithin() Mutates Data

copyWithin() reads elements within the range [start, end) and writes them sequentially starting at target. If the sequence to copy extends beyond the array’s boundary, it is trimmed to fit the existing array length.

const numbers = [10, 20, 30, 40, 50];

// Copy elements from index 3 to the end, paste at index 0
numbers.copyWithin(0, 3);
console.log(numbers); // Output: [40, 50, 30, 40, 50]

const items = ['a', 'b', 'c', 'd', 'e'];

// Copy elements from index 1 to 3 ('b', 'c'), paste at index 2
items.copyWithin(2, 1, 3);
console.log(items); // Output: ['a', 'b', 'b', 'c', 'e']

Like fill(), negative values for target, start, or end resolve relative to the end of the array. copyWithin() safely handles overlapping read and write regions by copying data in a way that avoids reading overwritten values.

Core Mutation Characteristics