JavaScript fill(): Overwrites a specified array by filling elements

The JavaScript fill() method overwrites a specified array by filling given elements. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p id="xyz"></p>
   
   <script>
      const nums = [1, 2, 3, 4];
      nums.fill(12);
      document.getElementById("xyz").innerHTML = nums;
   </script>
   
</body>
</html>
Output

JavaScript fill() syntax

The syntax of the fill() method in JavaScript is:

array.fill(value, startIndex, endIndex)

The value parameter is required, whereas the startIndex and endIndex parameters are optional.

Note: The startIndex and/or endIndex parameter(s) are used when we need to fill a particular index. The default value of startIndex is 0, whereas the default value of endIndex is Array Length.

JavaScript fill() example

Consider the following HTML and JavaScript code demonstrating the "fill()" method in JavaScript:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p id="abc"></p>
   
   <script>
      const numbers = [1, 2, 3, 4, 5, 6];
      numbers.fill(12, 2);
      document.getElementById("abc").innerHTML = numbers;
   </script>
   
</body>
</html>
Output

As you can see, the value 12 replaces all elements from index number 2 to the last.

Let me create another example that uses the fill() method with three parameters:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p id="myPara"></p>
   
   <script>
      const x = [1, 2, 3, 4, 5, 6];
      x.fill(12, 2, 4);
      document.getElementById("myPara").innerHTML = x;
   </script>
   
</body>
</html>
Output

In this example, the value 12 replaces all elements from index numbers 2 to 4. That is, the elements at index numbers 2 and 3 were replaced with 12. The last index, which is 4 in the above example, is excluded.

JavaScript Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!