Array unshift() method adds one or more elements to the beginning of an existing array and returns the new length of the array in Javascript.
Syntax is as below:
1 | array.unshift( item1, item2, ..., itemN ); |
item1, item2, itemN are elements to add to the front of array.
Return Value:
The return type is number, new length of the array. For IE browser this returns undefined.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 | <html> <head> <title>Array in JavaScript - unshift() Method</title> </head> <body> <script type="text/javascript"> var myArr = new Array("jQuery", "PHP", "HTML", "CSS"); var length = myArr.unshift("WordPress", "JavaScript"); document.write("Returned array is : " + arr ); document.write("<br /> Length of the array is : " + length ); </script> </body> </html> |
Output: This will result:
1 2 | Returned array is : WordPress,JavaScript,jQuery,PHP,HTML,CSS Length of the array is : 6 |
Try yourself the unshift() method example above. In this way you can add new array elements at the top of an array in JavaScript.