fill()
fill<
T>(array,value,start?,end?):T[]
Fills elements of array with value from start up to, but not including, end.
Unlike the native Array.fill() which mutates the original array, this function returns a new array, preserving immutability. See Design Philosophy
For ES2023+, consider using Array.toFilled().
Type Parametersโ
T: Tโ
The type of elements in the array.
Parametersโ
array: readonly T[]โ
The array to fill.
value: Tโ
The value to fill array with.
start?: numberโ
The start position.
end?: numberโ
The end position.
Returns: T[]โ
A new array with the filled values.
Sinceโ
2.0.0
Performanceโ
O(n) time & space โ three-pass manual copy with fill range.
Also known asโ
fill (Lodash, es-toolkit) ยท replaceOption (Effect) ยท โ (Remeda, Radashi, Ramda, Modern Dash, Antfu)
Exampleโ
const numbers = [1, 2, 3, 4, 5];
const filled = fill(numbers, 0, 1, 3);
console.log(filled); // [1, 0, 0, 4, 5]
console.log(numbers); // [1, 2, 3, 4, 5] (original unchanged)
How it works?โ
Replaces elements in a range with a specified value.
Unlike native Array.fill(), returns a new array (immutable).
Use Casesโ
Initialize game board or grid ๐โ
Create an array filled with a static initial value.
Immutable alternative to new Array(n).fill(v).
// Create a row of empty slots
const emptyRow = fill(new Array(5), "empty");
// => ["empty", "empty", "empty", "empty", "empty"]
Reset status flagsโ
Reset a specific range of values within an array without mutating the original. Useful for bulk updates or resetting state.
const steps = ["done", "done", "error", "pending"];
// Reset steps 1 and 2 (indices 1 to 3) to "retry"
const retrying = fill(steps, "retry", 1, 3);
// => ["done", "retry", "retry", "pending"]