← All languages
JavaScript function of the day
Random

Array.prototype.fill

Fill all or part of an array with a static value.

Description

The fill() method changes all elements within a specified range of an array to a static value. It returns the modified array. By default it fills the entire array, but optional start and end parameters allow you to target a specific section.

The start index is inclusive and the end index is exclusive. Negative indices are supported and are computed relative to the length of the array. If start is omitted, it defaults to 0; if end is omitted, it defaults to the array length.

This method mutates the original array in place. It is commonly used to initialize arrays with default values, reset portions of an array, or create arrays of a specific length pre-filled with a value using Array(n).fill(value).

Arguments

NameDescriptionOptional
value The value to fill the array with. No
start Zero-based start index (inclusive). Defaults to 0. Yes
end Zero-based end index (exclusive). Defaults to array length. Yes

Example

const arr = [1, 2, 3, 4, 5];
arr.fill(0, 2, 4);
console.log(arr); // [1, 2, 0, 0, 5]

const zeros = new Array(3).fill(0);
console.log(zeros); // [0, 0, 0]

Reference