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"]
Create a pixel grid for a canvas editorβ
Initialize a 2D grid of default color values for a pixel art editor. Essential for canvas-based drawing tools and tile map editors.
const width = 32;
const height = 32;
const grid = times(height, () => fill(new Array(width), "#ffffff"));
// => 32x32 grid of white pixels
// Paint a pixel
grid[10][15] = "#ff0000";
renderGrid(grid);
Generate skeleton loading rowsβ
Create placeholder rows for a table or list while data loads. Perfect for skeleton screens in dashboards and data tables.
const skeletonRows = fill(new Array(8), {
name: "",
email: "",
status: "loading",
});
// Render shimmer placeholders
skeletonRows.map((_, i) => <SkeletonRow key={i} />);