Whenever you use unshift() on an array, the method does the following:
- It adds its arguments to the beginning of its calling array.
- It returns the calling array’s new length.
Syntax of the unshift()
Method
unshift()
accepts one or more arguments. Here’s the syntax:
The item1, item2, ..., itemX
arguments signify the items you wish to add to the beginning of the calling array.
Examples of the unshift()
Method
Below are examples of the unshift()
method.
Add One New Item to the Beginning of an Array
Try it on StackBlitz
The snippet above used unshift()
to prepend an item (0
) to the beginning of the calling array.
Add Three New Items to the Beginning of an Array
Try it on StackBlitz
In the snippet above, the totalFruits
’ invocation returned 5
because unshift()
returned the calling array’s new length.