JavaScript fill() | Overwrites 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 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) is/are used when we need to fill for particular index. The default value of startIndex is 0, whereas the default value of endIndex is Array Length.

JavaScript fill() Example

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 number 2 to 4. That is, the elements at index number 2 and 3 was replaced with 12. The last index, that is 4 in above example, is excluded.

JavaScript Online Test


« Previous Tutorial Next Tutorial »