JavaScript Array fill() method


The fill() method in JavaScript is used to fill all the elements of an array with a static value from a specified start index to an end index. This method modifies the original array and can be useful for initializing or resetting array values.

Syntax:

array.fill(value, start, end);
  • value: The value to fill the array elements with. This can be any type of value, including objects or arrays.

  • start (optional): The index at which to start filling the array. The default is 0 (the beginning of the array).

  • end (optional): The index before which to stop filling the array (not inclusive). The default is the length of the array.

Return Value:

  • The modified array, with elements filled with the specified value.

Key Points:

  • The fill() method modifies the original array and returns it.
  • If start is greater than or equal to the array length, the method does nothing.
  • If end is less than or equal to start, the method fills nothing.
  • Negative values for start or end are treated as offsets from the end of the array.

Example 1: Basic usage

let numbers = [1, 2, 3, 4, 5]; numbers.fill(0); // Fill the entire array with 0 console.log(numbers); // [0, 0, 0, 0, 0]

Example 2: Specifying start and end indices

let numbers = [1, 2, 3, 4, 5]; numbers.fill(0, 1, 4); // Fill from index 1 to index 4 (not inclusive) console.log(numbers); // [1, 0, 0, 0, 5]

Example 3: Using negative indices

let numbers = [1, 2, 3, 4, 5]; numbers.fill(0, -3); // Fill starting from the third last element to the end console.log(numbers); // [1, 2, 0, 0, 0]

Example 4: Filling an empty array

let emptyArray = new Array(5); // Create an array with 5 empty slots emptyArray.fill('x'); // Fill with 'x' console.log(emptyArray); // ['x', 'x', 'x', 'x', 'x']

Example 5: Filling with an object

let obj = { key: 'value' }; let array = new Array(3).fill(obj); // Fill with a reference to the same object console.log(array); // [{ key: 'value' }, { key: 'value' }, { key: 'value' }] // Changing the object in one place affects all references array[0].key = 'new value'; console.log(array); // [{ key: 'new value' }, { key: 'new value' }, { key: 'new value' }]

Summary:

  • The fill() method is a powerful way to fill an array with a specified value, making it easy to initialize or reset array contents.
  • It is useful for preparing arrays for further manipulation or when you need to set default values.
  • Since it modifies the original array, care should be taken to avoid unintentional changes to existing data.