JavaScript shift(): Remove the First Element from an Array

The JavaScript shift() method is used to remove the first element from a specified array. For example:

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

   <p id="xyz"></p>
   
   <script>
      const x = [10, 20, 30, 40, 50];
      x.shift();
      document.getElementById("xyz").innerHTML = x;
   </script>
   
</body>
</html>
Output

JavaScript shift() syntax

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

array.shift()

The array.shift() method returns the removed or shifted element. For example:

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

   <p id="xyz"></p>
   
   <script>
      const arr = [10, 20, 30, 40, 50];
      document.getElementById("xyz").innerHTML = arr.shift();
   </script>
   
</body>
</html>
Output

JavaScript shift() example

Following is another example demonstrating the "shift()" method in JavaScript:

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

   <p>Original Array: <b><span id="original"></span></b></p>
   <p>New Array (after using shift()): <b><span id="reverse"></span></b></p>
   
   <script>
      const myArray = ["Tokyo", "Bangkok", "Dubai", "Berlin", "London"];
      document.getElementById("original").innerHTML = myArray;

      myArray.shift();
      document.getElementById("reverse").innerHTML = myArray;
   </script>
   
</body>
</html>
Output

Original Array:

New Array (after using shift()):

JavaScript Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!