Initialize slots
Create a fixed-size array with an initial value, such as null placeholders.
JavaScript · Function
Array.prototype.fill() replaces elements in a selected index range with one static value. It mutates the array and returns the modified array.
Call fill() on an array with the value to write and, optionally, a start index and an exclusive end index. It writes the same value into each selected position, including holes in sparse arrays, mutates the original array, and returns that array.
fill(value)
fill(value, start)
fill(value, start, end)| Name | Type | Description |
|---|---|---|
value | any | Value written into each selected array position. |
start | number | Optional zero-based starting index, converted to an integer; defaults to 0 when omitted. |
end | number | Optional zero-based exclusive ending index, converted to an integer; defaults to the array length when omitted or undefined. |
The modified array, filled with value.
const slots = Array(4).fill(null);
slots[1] = "reserved";
console.log(slots); // [null, "reserved", null, null]Creates four elements, then replaces one slot; fill() changes the original array and returns it.
Create a fixed-size array with an initial value, such as null placeholders.
Overwrite only a contiguous section of an existing array.
Populate an array-like object that exposes a length property.
fill() writes one value across an array index range and returns the modified array. The start index is inclusive, while the end index is exclusive.
Follow-up: What happens with negative bounds? They are interpreted relative to the array's end and then constrained to valid positions.
The method mutates the receiver but does not change its length. If no bounds are supplied, it fills from index 0 through the final index.
Follow-up: How would you avoid mutation? Create a shallow copy first, such as [...array], and call fill() on that copy.
value can be any value, including an object. Every selected slot receives that exact value, so object values are shared references rather than separately cloned objects.
Follow-up: What is a safe way to create independent objects per slot? Use Array.from with a mapping function instead of filling with one object.
ArrayArray.prototypeArray.fromTypedArray.prototype.fill