JavaScript Array fill() Method

JavaScript Array fill() method is used to fill specified elements in an array with a value. 

Syntax

array.fill(value, start, end)

Parameters

Parameter Description
value(required) It is the value to fill the array with
start(optional) The index to start filling the array (default index is 0)
end(optional) The index to stop filling the array (default is array. length)

If you do not provide the start and end index, it will replace the whole array with the provided value.

Return value

It returns the modified array.

Visual RepresentationVisual Representation of JavaScript Array fill() Method

Example 1: How to Use Array fill() method 

let alphabets = ['A', 'B', 'C', 'D', 'E'];
alphabets.fill('X'); 
console.log(alphabets);

Output

[ 'X', 'X', 'X', 'X', 'X' ]

Example 2: Passing start and end parameterVisual Representation of fill() method with start and end parameter

let num = [7,14,21,28,35];
num.fill(8,2,4); 
console.log(num);

Output

[ 7, 14, 8, 8, 35 ]

Example 3: Passing negative IndexVisual Representation of Passing negative Index

let num = [7,14,21,28,35];
num.fill(9,-3); 
console.log(num);

Output

[ 7, 14, 9, 9, 9 ]

Example 4: Start index is greater than a length

let num = [7,14,21,28,35];
num.fill(9,5,7); 
console.log(num);

Output

[ 7, 14, 21, 28, 35 ]

In the above example, starting index 5 is beyond the last index of the array. So, no elements will be modified.

Example 5: Passing NaN as an argument

If the start and end number is not a number or NaN, it will not modify the array.

let num = [7,14,21,28,35];
num.fill(9,NaN,NaN); 
console.log(num);

Output

[ 7, 14, 21, 28, 35 ]

Example 5: populating an empty array

const data = Array(5).fill("Ronaldo", 0);

console.log(data)

Output

[ 'Ronaldo', 'Ronaldo', 'Ronaldo', 'Ronaldo', 'Ronaldo' ]

Example 6: Using non-array objects

const data = { length: 6 }

console.log(Array.prototype.fill.call(data, 1))

Output

{ '0': 1, '1': 1, '2': 1, '3': 1, '4': 1, '5': 1, length: 6 }

Browser compatibility

  1. Google Chrome 45
  2. Microsoft Edge 12
  3. Firefox 31
  4. Safari 8
  5. Opera 32

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.