Javascript - Array fill() Method

The fill() method fills all the elements in an array with a static value.

Description

The fill() method fills all the elements in an array with a static value.

You can specify the index for starting and ending fill(). By default it changes the whole array.

Array fill() method can fill all the elements of an array with a static value.

It also takes optional start and end index values.

[1, 2, 3].fill(4);         // [4, 4, 4] 
[1, 2, 3].fill(4, 1);      // [1, 4, 4] 
[1, 2, 3].fill(4, 1, 2);   // [1, 4, 3] 

The input value can be arbitrary, not necessarily a number, character, or any other primitive type. It can be an object, for example:

new Array(4).fill({});     // [{}, {}, {}] 

Syntax

array.fill(value, start, end)

Parameter Values

Parameter Require Description
value Required. The value to fill the array with
start Optional. The index to start filling the array (default is 0)
end Optional. The index to stop filling the array (default is array.length)

Return

An Array, the changed array

Example

Fill all the array elements with a static value:

Demo

var myArray = ["XML", "Json", "Database", "Mango"];
console.log( myArray);//w  ww. ja  va2 s .  c  o  m

console.log( myArray.fill("new value"));

//Fill the last two array elements with a static value:

var myArray = ["XML", "Json", "Database", "Mango"];
console.log( myArray);

console.log( myArray.fill("new",2,4));

Result