I have an array like [23, 45, 12, 67], and when I get a new element (say 34) from an AJAX response, I want to update the array to [34, 23, 45, 12, 67].
I currently loop through the array and rebuild it, but I’m wondering if JavaScript offers a more optimal or cleaner way to handle array insert at 0.
Yes, JavaScript gives you a direct method for this!
You can use unshift() to insert an element at the beginning:
theArray.unshift(response);
This modifies the original array and adds the element to index 0. Simple, readable, and native.
If you’re working with immutable data (e.g., in functional programming or React state), then use:
theArray = [response, ...theArray];
This creates a new array without mutating the original one.
It’s concise and expressive.
Your current method (manually creating a new array) has similar complexity to unshift()—both are O(n) because all existing elements must shift, but unshift() is optimized and more idiomatic.
Unless you’re handling millions of items and profiling for performance, stick with unshift() for clarity and efficiency.