Computer >> Computer tutorials >  >> Programming >> Javascript

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


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:

<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