JavaScript Array fill()

Posted by

JavaScript Array fill() Method

The JavaScript Array.fill() method is used to fill all the elements of an array with a static value. It is a mutable method, meaning that it changes the original array it is called upon. The syntax of the fill() method is:

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

arr.fill(value[, start[, end]])

[/dm_code_snippet]

The value parameter is required, and is the value to fill the array with. The start and end parameters are optional, and specify the start and end index of the array to fill. If the start parameter is omitted, the filling will begin at index 0. If the end parameter is omitted, the filling will continue until the last index of the array.

The fill() method returns the modified array.

Examples

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

In this example, we will create an array of five elements and fill it with the value ‘A’:

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

// Create an array with 5 elements
let arr = new Array(5);

// Fill the array with 'A'
arr.fill('A');

console.log(arr); // [ 'A', 'A', 'A', 'A', 'A' ]

[/dm_code_snippet]

In this example, we will again create an array of five elements and fill it with the value ‘A’, but this time, we will specify the start and end indexes of the array to fill:

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

// Create an array with 5 elements
let arr = new Array(5);

// Fill the array with 'A'
arr.fill('A', 1, 3);

console.log(arr); // [ , 'A', 'A', ,  ]

[/dm_code_snippet]

Browser Support

The Array.fill() method is supported in all modern browsers, including Internet Explorer 9 and higher.