In a previous article, we broke down how pop()
and push()
work under the hood in JavaScript. If you haven’t read that yet, I recommend checking it out first so this one makes even more sense. You can read it here if you're curious about how arrays handle adding and removing items from the end.
In this article, we’re looking at the other side: shift()
and unshift()
. Let’s break them down together.
Array.unshift(new_item)
This array method is used when you want to add an item to the beginning of an array. Unlike push(), it's not as cheap. It has a time complexity of O(n), linear time.
If you have an array and you want to add something to the front, i.e index 0, JavaScript has to move every other item one step forward to make space. Imagine shifting people in a line forward to make room for one more at the start. That takes time. Let’s look at what unshift() does under the hood.
const jsUnshift = (arr, newItem) => {
let newArr = [newItem];
for (let i = 0; i < arr.length; i++) {
newArr[i + 1] = arr[i];
}
return newArr;
};
console.log(jsUnshift([1, 2, 3, 4], 0));
//result: [0,1,2,3,4]
JavaScript must make space at index 0. So, it shifts every existing element one position to the right. Another way to do this is:
const numArray = [2, 3, 4];
const jsUnshift = (arr, newItem) => {
for (let i = arr.length; i > 0; i--) {
arr[i] = arr[i - 1];
}
arr[0] = newItem;
return arr;
};
console.log(jsUnshift(numArray, 1));
//result ==> [1,2,3,4]
The time it takes to perform this operation grows with the size of the array. Hence, the time complexity is O(n).
Array.shift()
Now for the opposite. shift() removes the first item in the array. It sounds simple, but like unshift(), its time complexity is O(n), linear time.
Why? Because when the first item is removed, all the other items need to shift one place to the left so the array stays in order. Again, we’re moving stuff.
const jsShift = (arr) => {
if (arr.length === 0) return undefined;
for (let i = 0; i < arr.length; i++) {
arr[i] = arr[i + 1];
}
arr.length = arr.length - 1;
return arr;
};
console.log(jsShift([1, 3, 4]));
//result ==> [3,4]
Conclusion
While shift()
and unshift()
may seem straightforward, they’re doing more work behind the scenes than methods like push()
and pop()
. Because arrays are zero-indexed, inserting or removing items from the beginning means all other elements must be re-indexed, making these operations O(n) in time complexity.
So, the next time you use shift()
or unshift()
, remember: JavaScript is quietly doing a lot of heavy lifting to maintain the order of your array.
Understanding this can help you make better performance decisions, especially when working with large arrays or performance-critical code.
Top comments (0)