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

 Live Demo

<!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

Click “Fill” button to fill the array −

Example

 Live Demo

<!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

Click “Fill” to fill the array −

Updated on: 17-Dec-2019

240 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements