๐ INDEX
JS unshift()
Add elements to the start of an array. Learn syntax, mutation, and performance.
// Initializing array...
Tutor: The unshift() method adds one or more elements to the BEGINNING of an array. Unlike push(), which adds to the end, unshift() shifts existing elements to a higher index.
Syntax & Parameters
The unshift() method accepts one or more arguments to add.
- Returns: The new
lengthproperty of the array. - Mutation: Yes, it modifies the original array.
Unshift vs Push
| Method | Position | Complexity |
|---|---|---|
| unshift() | Start | O(n) - Slowest |
| push() | End | O(1) - Fastest |
Note: unshift() is slower because it re-indexes every item.
Achievements
Start Specialist
Successfully add elements to the beginning of an array.
Array Mutator
Understand how unshift changes array length.
Logic Architect
Master multi-element unshifting.
Detailed Explanation
When you use unshift(), you aren't just placing an item. You are asking the JavaScript engine to move every single existing item in that array one slot to the right. If the array contains 1,000,000 items, unshift() performs 1,000,000 operations.
This is why for large datasets, developers often use push() and reverse(), or different data structures like Linked Lists if constant insertion at the beginning is required.