Computer >> Computer tutorials >  >> Programming >> Javascript

JavaScript Array fill() function


The fill() method of JavaScript is used to fill the elements in an array with a static value.

The syntax is as follows −

array.fill(val, start, end)

Above, val is the value to fill the array, start is the index to begin filling the array, whereas end is the index to stop filling the array.

Let us now implement the fill() method in JavaScript −

Example

<!DOCTYPE html>
<html>
<body>
   <h2>Ranking Points</h2>
   <button onclick="display()">Fill</button>
   <p id="demo"></p>
   <script>
      var pointsArr = [50, 100, 200, 300, 400, 500, 600];
      document.getElementById("demo").innerHTML = pointsArr;
      function display() {
         document.getElementById("demo").innerHTML = pointsArr.fill(1000);
      }
   </script>
</body>
<!DOCTYPE html>

Output

JavaScript Array fill() function

Click “Fill” button to fill the array −

JavaScript Array fill() function

Example

<!DOCTYPE html>
<html>
<body>
   <h2>Student Name</h2>
   <button onclick="display()">Fill</button>
   <p id="demo"></p>
   <script>
      var stdName = ["John", "Tom", "David"];
      document.getElementById("demo").innerHTML = stdName;
      function display() {
         document.getElementById("demo").innerHTML = stdName.fill("Jacob");
      }
   </script>
</body>
<!DOCTYPE html>

Output

JavaScript Array fill() function

Click “Fill” to fill the array −

JavaScript Array fill() function