JavaScript unshift() method
The unshift()
method in JavaScript is used to add one or more elements to the beginning of an array. It modifies the original array by inserting new elements at the start and returns the new length of the array.
Syntax:
element1, element2, ..., elementN
: The elements you want to add to the beginning of the array.
Return Value:
- Number: The new length of the array after the elements have been added.
Key Points:
- Modifies the original array: The
unshift()
method changes the original array by inserting new elements at the front. - Returns the new length: It returns the updated length of the array.
- Inserts multiple elements: You can add one or more elements at the start of the array.
Example 1: Adding one element to the array
Example 2: Adding multiple elements at once
Example 3: Using unshift()
with an empty array
Performance Consideration:
- Time complexity: The time complexity of
unshift()
is O(n), wheren
is the number of elements in the array. This is because adding elements at the beginning requires shifting all existing elements to higher indices.
Summary:
unshift()
adds one or more elements to the beginning of an array, modifying the original array. It returns the new length of the array and allows multiple elements to be added in a single call. However, it may be less efficient than adding elements to the end (usingpush()
) for large arrays because existing elements need to be re-indexed.