JavaScript | Array unshift()

arr.unshift() is used to add one or more elements to the beginning of the given array. This function increases the length of the existing array by the number of elements added to the array. The syntax of the function is as follows:

arr.unshift(element1[, ...[, elementN]])

Arguments
The number of arguments to this function is same as the number of elements to be added at the beginning of the array.

Return value
This function returns the new length of the array after inserting the arguments at the beginning of the array.



Example for the above function is provided below:

Example 1:

var arr = [23,76,19,94];
print(arr.unshift(28,65));
print(arr);

Output:

6
28,65,23,76,19,94

In this example the function unshift() adds 28 and 65 to the front of the array.

Code for the above function is provided below:

Program 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// JavaScript to illustrate unshift() function
<script>
function sayHello() {
    var arr = [23,76,19,94];
      
    // Adding elements to the front of the array
    document.write(arr.unshift(28,65));
    document.write("<br>");
    document.write(arr);
}
sayHello();
</script>

chevron_right


Output:

6
[28,65,23,76,19,94]


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.