Friday, July 5, 2024
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!

Shaida Kate Naidoo
am passionate about learning the latest technologies available to developers in either a Front End or Back End capacity. I enjoy creating applications that are well designed and responsive, in addition to being user friendly. I thrive in fast paced environments. With a diverse educational and work experience background, I excel at collaborating with teams both local and international. A versatile developer with interests in Software Development and Software Engineering. I consider myself to be adaptable and a self motivated learner. I am interested in new programming technologies, and continuous self improvement.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments