JavaScript Array shift()

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

The shift() method of JavaScript is used to remove the first item of an array.

The syntax is as follows −

array.shift()

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

Example

 Live Demo

<!DOCTYPE html>
<html>
<body>
   <h2>Demo Heading</h2>
   <p id="test"></p>
   <script>
      var arrStud = ["Laptop", "Desktop", "Tablet"];
      document.getElementById("test").innerHTML = "Initial array = "+arrStud+", <br>Removed first             element = "+arrStud.shift();
   </script>
</body></html>

Output

Example

 Live Demo

<!DOCTYPE html>
<html>
<body>
   <h2>Car Variant</h2>
   <button onclick="display()">Result</button>
   <p id="test"></p>
   <script>
      var car = ["Hatchback", "Convertible", "SUV", "AUV", "MUV"];
      document.getElementById("test").innerHTML = "Initial Array = "+car;
      function display() {
         car.shift();
         document.getElementById("test").innerHTML = "Array after removing the 1st element = "+car;
      }
   </script>
</body></html>


Output

Click “Result” above −

raja
Published on 17-Dec-2019 07:52:18
Advertisements