• JavaScript Video Tutorials

JavaScript - Array shift() Method



The JavaScript Array.shift() method is used to remove the first element from an array and returns the removed element. This method reduces the length of the original array by one. When we call this method on the empty array, it returns "undefined". After removing an element at the 0th index, the remaining values in the array are shifted downwards to occupy consecutive indexes.

If we want to remove the last element of an array, use the JavaScript Array.pop() method.

Syntax

Following is the syntax of JavaScript Array shift() method −

array.shift();

Parameters

This method does not accept any parameters.

Return value

This method returns the removed element from the beginning of the array. If the array is empty, it returns undefined.

Examples

Example 1

In the following example, we are using the JavaScript Array shift() method to remove the first item of an array.

<html>
<body>
   <p id="demo"></p>
   <script>
      const animals = ["Lion", "Cheetah", "Tiger", "Elephant"];
      animals.shift();
      document.getElementById("demo").innerHTML = animals;
   </script>
</body>
</html>

Output

As we can see the output, the first element of the array is shifted.

Cheetah,Tiger,Elephant

Example 2

Here, we are fetching the shifted element from the specified array −

<html>
<body>
   <p id="demo"></p>
   <script>
      const animals = ["Lion", "Cheetah", "Tiger", "Elephant"];
      let result = animals.shift();
      document.getElementById("demo").innerHTML = result;
   </script>
</body>
</html>

Output

The output shows the shifted element from the array.

Lion
Advertisements