Open In App
Related Articles

How to perform unshift operation without using unshift() method in JavaScript ?

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report
The task is to perform unshift operation without using the unshift() method with the help of jQuery. There are two approaches that are discussed below: Approach 1: We can use the Array concat() method which is used to join two or more arrays. Just pass the newElement as the arrays of size 1 and the rest of the array.
  • Example:
    <!DOCTYPE HTML>
    <html>
      
    <head>
        <title>
            How to perform the unshift() operation 
            without using it in JavaScript
        </title>
    </head>
      
    <body style="text-align:center;">
        <h1 style="color:green;"
                GeeksforGeeks 
        </h1>
        <p id="GFG_UP">
        </p>
        <button onclick="myGFG()">
            Click Here
        </button>
        <p id="GFG_DOWN">
        </p>
        <script>
            var array = ['Geeks', 'GFG', 'Geek', 'GeeksforGeeks'];
            var up = document.getElementById("GFG_UP");
            up.innerHTML = "Array = [" + array + "]";
            var down = document.getElementById("GFG_DOWN");
      
            function myGFG() {
                var newElement = 'gfg';
                newArray = [newElement].concat(array);
                down.innerHTML = "Elements of array = ["
                                  + newArray + "]";
            }
        </script>
    </body>
      
    </html>
    
                        
  • Output:
Approach 2: We can use the ES6 spread operator to perform the operation.
  • Example:
    <!DOCTYPE HTML>
    <html>
      
    <head>
        <title>
            How to perform the unshift() operation without 
            using it in JavaScript
        </title>
    </head>
      
    <body style="text-align:center;">
        <h1 style="color:green;"
                GeeksforGeeks 
        </h1>
        <p id="GFG_UP">
        </p>
        <button onclick="myGFG()">
            Click Here
        </button>
        <p id="GFG_DOWN">
        </p>
        <script>
            var array = ['Geeks', 'GFG', 'Geek', 'GeeksforGeeks'];
            var up = document.getElementById("GFG_UP");
            up.innerHTML = "Array = [" + array + "]";
            var down = document.getElementById("GFG_DOWN");
      
            function myGFG() {
                var newElement = 'gfg';
                newArray = [newElement, ...array];
                down.innerHTML = "elements of array = ["
                                + newArray + "]";
            }
        </script>
    </body>
      
    </html>
    
                        
  • Output:


Last Updated : 15 Apr, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads