JavaScript Array fill()

Posted by

Method

JavaScript Array fill() Method

The fill() method is used to fill the specified elements in an array with a static value. It is a mutable method, which means that it changes the original array.

Syntax

array.fill(value, start, end)

  • value: The value to fill the array with.
  • start: The index to start filling the array (default is 0).
  • end: The index to stop filling the array (default is array.length).

Example 1: Filling the whole array

Let’s fill the whole array with the number 9:

[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”]

let numbers = [1, 2, 3, 4, 5];
numbers.fill(9);
console.log(numbers); 
// Output: [9, 9, 9, 9, 9]

[/dm_code_snippet]

Example 2: Filling a section of the array

Let’s fill a section of the array, starting at index 2 and ending at index 4, with the number 6:

[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”]

let numbers = [1, 2, 3, 4, 5];
numbers.fill(6, 2, 4);
console.log(numbers); 
// Output: [1, 2, 6, 6, 5]

[/dm_code_snippet]

Example 3: Filling an array with an object

Let’s fill the array with an object:

[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”]

let numbers = [1, 2, 3, 4, 5];
let obj = {name: "John"};
numbers.fill(obj);
console.log(numbers); 
// Output: [{name: "John"}, {name: "John"}, {name: "John"}, {name: "John"}, {name: "John"}]

[/dm_code_snippet]

Browser Support

The fill() method is supported in all major browsers.