• JavaScript Video Tutorials

JavaScript - Array fill() Method



The JavaScript Array.fill() method is used to fill all the elements of an array with a specified value. The fill() method modifies the original array in place and returns the modified array. It does not create a new array.

Following is the behaviour of JavaScript Array.fill() method −

  • If "start" is negative, it is treated as array.length + start.
  • If "end" is negative, it is treated as array.length + end.
  • If "start" is greater than or equal to end, the array will not be modified.

Syntax

Following is the syntax of JavaScript Array fill() method −

array.fill(value, start, end);

Parameters

This method accepts three parameters. The same is described below −

  • value − The value to fill the array with.
  • start (optional) − The index from which to start filling the array. If not provided, the default value is 0.
  • end (optional)− The index at which to stop filling the array. If not provided, the array is filled up to its last index.

Return value

This method modifies the original array and returns the modified array.

Examples

Example 1

In the following example, we are filling all the elements with the value “Dinosaur” using the JavaScript Array fill() method −

<html>
<body>
   <p id="demo"></p>
   <script>
      const animals = ["Lion", "Cheetah", "Tiger", "Elephant"];
      document.getElementById("demo").innerHTML = animals.fill("Dinosaur");
   </script>
</body>
</html>

Output

As we can see the output, all the elements in the array are filled with "Dinosaur".

Dinosaur,Dinosaur,Dinosaur,Dinosaur

Example 2

Here, we are passing a specified value “Dinosaur” and a start index "2" to the fill() function.

<html>
<body>
   <p id="demo"></p>
   <script>
      const animals = ["Lion", "Cheetah", "Tiger", "Elephant"];
      document.getElementById("demo").innerHTML = animals.fill("Dinosaur", 2);
   </script>
</body>
</html>

Output

After executing the above program, the third and fourth element of the array will be filled with "Dinosaur".

Lion,Cheetah,Dinosaur,Dinosaur

Example 3

The following program fills the value “Dinosaur” from the second element to fourth element of the array.

<html>
<body>
   <p id="demo"></p>
   <script>
      const animals = ["Lion", "Cheetah", "Tiger", "Elephant"];
      document.getElementById("demo").innerHTML = animals.fill("Dinosaur", 1, 4);
   </script>
</body>
</html>

Output

After executing the above program, from the second element to fourth element, it will be filled with the value "Dinosaur".

Lion,Dinosaur,Dinosaur,Dinosaur
Advertisements