How to add new array elements at the beginning of an array in JavaScript?

JavascriptWeb DevelopmentFront End Technology

JavaScript array unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.

Example

You can try to run the following code to learn how to add new array elements at the beginning of an array:

Live Demo

<html>    
   <head>      
      <title>JavaScript Array unshift Method</title>    
   </head>      
   <body>          
      <script>          
         var arr = new Array("orange", "mango", "banana", "sugar");                    
         var length = arr.unshift("water");          
         document.write("Returned array is : " + arr );          
         document.write("<br /> Length of the array is : " + length );      
     </script>          
   </body>
</html>                                                                                

Output

Returned array is : water,orange,mango,banana,sugar
Length of the array is : 5
raja
Published on 22-Apr-2018 21:24:07
Advertisements