Open In App

JavaScript Array fill() Method

Improve
Improve
Like Article
Like
Save
Share
Report

The fill() method in JavaScript is used to fill all the elements of an array from a start index to an end index with a static value.

It mutates the original array and returns the modified array.

Syntax:

arr.fill(value, start, end)

Parameters:

This method accepts three parameters as described below: 

Parameter

Description

value

It defines the static value with which the array elements are to be replaced.

start

(Optional), It defines the starting index from where the array is to be filled with the static value. If this value is not defined the starting index is taken as 0. If the start is negative then the net start index is length+start.

end

(Optional), This argument defines the last index up to which the array is to be filled with the static value. If this value is not defined then by default the last index of the i.e arr. length – 1 is taken as the end value. If the end is negative, then the net end is defined as length+end.

Return value:

This method does not return a new array. Instead of it modifies the array on which this method is applied.

JavaScript Array fill() Method Examples

Example 1: Filling Array with a Specified Value using JavaScript’s fill() Method

The function initializes an array with values. It then uses fill() to replace all elements with the value 87. The modified array [87, 87, 87, 87] is logged to the console.

JavaScript
// JavaScript code for fill() method
function func() {
    let arr = [1, 23, 46, 58];

    // fill array with 87
    arr.fill(87);
    console.log(arr);
}
func();

Output
[ 87, 87, 87, 87 ]

Example 2: Custom Range Filling with JavaScript’s fill() Method

The function initializes an array with values. Using fill(), it replaces elements from index 1 to 3 (exclusive) with the value 87. The modified array [1, 87, 87, 58] is logged to the console.

JavaScript
// JavaScript code for fill() method
function func() {
    let arr = [1, 23, 46, 58];

    // here value = 87, start index=1 and
    // and last index = 3
    arr.fill(87, 1, 3);
    console.log(arr);
}
func();

Output
[ 1, 87, 87, 58 ]

We have a complete list of Javascript Array methods, to check those please go through this Javascript Array Complete reference article.

Supported Browsers: The browsers supported by the JavaScript Array fill() method are listed below: 

We have a Cheat Sheet on Javascript where we covered all the important topics of Javascript to check those please go through Javascript Cheat Sheet-A Basic guide to JavaScript


Last Updated : 14 Mar, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads