Skip to content
Related Articles

Related Articles

What is the difference between unshift() and Push() method in JavaScript?
  • Last Updated : 01 Feb, 2021

JavaScript Unshift() method is very much similar to the push() method but the difference is that the unshift() method adds the elements in the very beginning of array whereas the push() method adds at the end of the array.

The following points list the common ones.

Both methods are used to add the elements to the array. 

  • Both methods change the length of the array by the number of elements added to the array.
  • Both methods are used to increase the length of the array.
  • Both unshift() and push() are the in-built methods of the object array.
  • Both method changes the original array.
  • Both method returns the newly added element.

Difference between Unshift() and Push():

The little difference is that unshift() method adds the element at 0 index and all the values get shifted by 1 by ultimately returning the length of the array. The push() method returns the last element adding a new element from the last index.



Example: Below is the example of Array unshift() method.

Javascript




<script> 
function func() { 
      
    // Original array 
    var array = ["GFG", "Geeks", "for", "Geeks"]; 
  
    // Checking for condition in array 
    var value = array.unshift("GeeksforGeeks"); 
  
    document.write(value); 
    document.write("<br />"); 
    document.write(array); 
  
func(); 
</script> 

Output:

GeeksforGeeks,GFG,Geeks,for,Geeks. 

Example 2: Below is the example of Array push() method. 

Javascript




<script> 
    function func() { 
        var arr = ['GFG', 'gfg', 'g4g']; 
      
        // Pushing the element into the array 
        arr.push('GeeksforGeeks'); 
                document.write(arr); 
      
    
    func(); 
</script>                 

Output: 

GFG,gfg,g4g,GeeksforGeeks 
My Personal Notes arrow_drop_up
Recommended Articles
Page :