Array.fill()

The Array.fill() method in JavaScript is used to fill all or part of an array with a static value. You can specify the start and end indices for the portion of the array to fill. This method modifies the original array and returns it.

Syntax

</>
Copy
fill(value)
fill(value, start)
fill(value, start, end)

Parameters

ParameterDescription
valueThe value to fill the array with.
start (optional)The index at which to start filling. Default is 0.
end (optional)The index at which to stop filling (not inclusive). Default is the array’s length.

Return Value

The fill() method returns the modified array after filling it with the specified value.


Examples

1. Filling the Entire Array

In this example, the entire array is filled with the specified value.

</>
Copy
const array = [1, 2, 3, 4, 5];

array.fill(0);
console.log(array);

Output

[0, 0, 0, 0, 0]
  1. array.fill(0) replaces all elements in the array with 0.

2. Filling Part of the Array

This example demonstrates how to fill only a portion of the array, starting from a specific index.

</>
Copy
const array = [1, 2, 3, 4, 5];

array.fill(9, 2);
console.log(array);

Output

[1, 2, 9, 9, 9]
  1. array.fill(9, 2) starts filling the array with 9 from index 2 to the end.

3. Filling with a Start and End Index

You can specify both the start and end indices for the portion of the array to fill.

</>
Copy
const array = [1, 2, 3, 4, 5];

array.fill(7, 1, 4);
console.log(array);

Output

[1, 7, 7, 7, 5]
  1. array.fill(7, 1, 4) fills the array with 7 from index 1 to 4 (exclusive).

4. Filling an Empty Array

The fill() method can initialize an empty array with specific values.

</>
Copy
const array = new Array(5);

array.fill('A');
console.log(array);

Output

['A', 'A', 'A', 'A', 'A']

An empty array of size 5 is filled with the value 'A'.

5. Filling with Non-Primitive Values

When using objects, all references in the array point to the same object.

</>
Copy
const array = new Array(3);

const obj = { key: 'value' };
array.fill(obj);

console.log(array);

obj.key = 'new value';
console.log(array);

Output


[ { key: 'value' }, { key: 'value' }, { key: 'value' } ]
[ { key: 'new value' }, { key: 'new value' }, { key: 'new value' } ]
  1. All elements share the same reference to obj, so modifying obj affects all elements in the array.