How to Use Shift and Unshift in JavaScript Arrays
In JavaScript,
shift() removes the first element from an array and returns it, changing the array length. unshift() adds one or more elements to the start of an array and returns the new length of the array.Syntax
shift() removes the first element of an array and returns it. It changes the original array.
unshift(element1, element2, ...) adds one or more elements to the start of an array and returns the new length of the array.
javascript
array.shift(); array.unshift(element1, element2, ...);
Example
This example shows how shift() removes the first item and returns it, and how unshift() adds new items to the start of the array.
javascript
const fruits = ['apple', 'banana', 'cherry']; const first = fruits.shift(); console.log('Removed:', first); // 'apple' console.log('After shift:', fruits); // ['banana', 'cherry'] const newLength = fruits.unshift('mango', 'pineapple'); console.log('New length:', newLength); // 4 console.log('After unshift:', fruits); // ['mango', 'pineapple', 'banana', 'cherry']
Output
Removed: apple
After shift: [ 'banana', 'cherry' ]
New length: 4
After unshift: [ 'mango', 'pineapple', 'banana', 'cherry' ]
Common Pitfalls
- Using
shift()on an empty array returnsundefined. unshift()changes the original array length, so be careful when relying on array size.- Both methods modify the original array, so if you want to keep the original array unchanged, make a copy first.
javascript
const arr = []; const removed = arr.shift(); console.log(removed); // undefined const length = arr.unshift('new'); console.log(length); // 1 console.log(arr); // ['new']
Output
undefined
1
[ 'new' ]
Quick Reference
| Method | What it does | Returns | Modifies original array? |
|---|---|---|---|
| shift() | Removes first element | Removed element or undefined if empty | Yes |
| unshift(...elements) | Adds elements to start | New length of array | Yes |
Key Takeaways
Use shift() to remove and get the first element of an array.
Use unshift() to add one or more elements to the start of an array.
Both methods change the original array directly.
shift() returns undefined if the array is empty.
unshift() returns the new length of the array after adding elements.