Shift() vs pop() methods in JavaScript?



Shift() vs pop()

Shift() and pop() methods are used to remove an element from an array. But there is a slight variation between them. The method shift() is used to remove the first element from an array, whereas the pop() method is used to remove the last method from the array. Let's discuss them in detail.

Shift()

Using this method we can remove the first element of an array.

syntax

array.shift();

Example

In the following example, there are 4 elements in the array. When the shift() method is used the first element was removed and the remaining array is displayed as shown in the output.

<html>
<body>
<script>
   var companies = ["Tesla", "Spacex", "Hyperloop", "Solarcity"];
   document.write("Before shift:" +" "+ companies );
   companies .shift();
   document.write("</br>");
   document.write("After shift:" +" "+ companies );
</script>
</body>
</html>

Output

Before shift: Tesla,Spacex,Hyperloop,Solarcity
After shift: Spacex,Hyperloop,Solarcity

pop()

syntax

array.pop();

Example

In the following example, there are 4 elements in the array. When the pop() method is used the last element was removed and the remaining array is displayed as shown in the output.

<html>
<body>
<script>
   var companies = ["Tesla", "Spacex", "Hyperloop", "Solarcity"];
   document.write("Before pop:" +" "+ companies );
   companies .pop();
   document.write("</br>");
   document.write("After pop:" +" "+ companies );
</script>
</body>
</html>

Output

Before pop: Tesla,Spacex,Hyperloop,Solarcity
After pop: Tesla,Spacex,Hyperloop
raja
Published on 19-Aug-2019 13:22:33
Advertisements