The fill() method in Javascript is used to change the elements of an array with a specified value. We can specify a start and end index for this method. If the start and end index is not set, it fills all the array elements with the given value. The fill() method overwrites the original array.

Let’s look at examples of using the fill() method.

​​​​let numbers = Array(5).fill(0);

console.log(numbers); // [0, 0, 0, 0, 0]

In the above example, we created an empty array with 5 elements and then chained the fill() method with the value 0. This way each element in the array is assigned a value 0.

We can also overwrite an existing array using the fill() method. For example,

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

numbers.fill(0);

console.log(numbers); // [0, 0, 0, 0, 0]

start and end index

The fill() comes with additional start and end index parameters to specify the range that needs to be filled with the given value. Let’s say we want only the first 4 elements of an array to be filled with the value 0.

let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];

numbers.fill(0, 0, 4);

console.log(numbers); // [0, 0, 0, 0, 5, 6, 7, 8, 9]

Here, the second parameter is the start index with the value 0 and the second parameter is the end index(exclusive) with the value 4.

Similarly,

let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];

numbers.fill(0, 4, 7);

console.log(numbers); // [1, 2, 3, 4, 0, 0, 0, 8, 9]

If you don’t specify the end index, it takes array.length as the default value.

let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];

numbers.fill(0, 4);

console.log(numbers); // [1, 2, 3, 4, 0, 0, 0, 0, 0]