Sunday, November 17, 2024
Google search engine
HomeLanguagesJavascriptShift() vs pop() Method in JavaScript

Shift() vs pop() Method in JavaScript

JavaScript shift() and pop() methods are used to remove an element from an array. But there is a little difference between them. The shift() method removes the first element and whereas the pop() method removes the last element from an array. 

Javascript Array shift() method: The JavaScript Array shift() Method removes the first element of the array thus reducing the size of the original array by 1.

Syntax:

arr.shift()

Example: Below is an example of the array shift() method

Javascript




<script>
    function func() { 
          
        // Original array 
        var array = ["GFG", "Geeks", "for", "Geeks"]; 
      
        // Checking for condition in array 
        var value = array.shift(); 
      
        console.log(value); 
        console.log(array); 
    
      
    func(); 
</script>


Output: 

GFG
Geeks, for, Geeks

Javascript Array pop() method: The JavaScript Array pop() Method is used to remove the last element of the array and also returns the removed element. This function decreases the length of the array.

 Syntax:

arr.pop()

Example: Below is the example of the array pop() method.

Javascript




<script>
    function func() { 
        var arr = ['GFG', 'gfg', 'g4g', 'neveropen']; 
      
        // Popping the last element from the array 
        console.log(arr.pop());
    
    func(); 
</script>


Output:  

neveropen

Difference Table:

Javascript Array shift() method Javascript Array pop() method
This method removes the first element from the array. This method removes the last element from the array.
This method shifts the indexes of the elements by -1. This method removes the last index of the array.
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments