How can I add new elements at the beginning of an array in JavaScript?
I need to prepend elements to an existing array. For example, if my array is:
[23, 45, 12, 67]
And I receive a value of 34 from an AJAX call, I want the updated array to be:
[34, 23, 45, 12, 67]
Currently, I’m implementing this approach:
var newArray = [];
newArray.push(response);
for (var i = 0; i < theArray.length; i++) {
newArray.push(theArray[i]);
}
theArray = newArray;
delete newArray;
Is there a more efficient way to accomplish this? Does JavaScript have built-in methods for prepending elements to arrays? My current solution has O(n) complexity, and I’m interested in exploring better implementations.
The most efficient way to add elements at the beginning of a JavaScript array is using the built-in unshift() method, which modifies the array in-place with O(n) time complexity but is more concise and optimized than manual iteration. For a modern approach, you can also use the spread operator [34, ...theArray] which provides cleaner syntax while maintaining similar performance.
Contents
- Using unshift() Method
- Modern Spread Operator Approach
- Alternative Methods
- Performance Comparison
- Best Practices
- Browser Compatibility
- Immutable Alternatives
Using unshift() Method
The unshift() method is the most direct and built-in way to add elements to the beginning of an array. It modifies the original array and returns the new length.
let theArray = [23, 45, 12, 67];
let response = 34;
// Add single element to beginning
theArray.unshift(response);
console.log(theArray); // [34, 23, 45, 12, 67]
// Add multiple elements
theArray.unshift(1, 2, 3);
console.log(theArray); // [1, 2, 3, 34, 23, 45, 12, 67]
The unshift() method is highly optimized by JavaScript engines and is the most memory-efficient solution since it works directly on the existing array without creating new arrays.
Modern Spread Operator Approach
ES6 introduced the spread operator, which provides a concise and readable way to create new arrays with prepended elements:
let theArray = [23, 45, 12, 67];
let response = 34;
// Single element
let newArray = [response, ...theArray];
console.log(newArray); // [34, 23, 45, 12, 67]
// Multiple elements
let anotherArray = [1, 2, 3, ...theArray];
console.log(anotherArray); // [1, 2, 3, 23, 45, 12, 67]
This approach creates a new array rather than modifying the original, which can be beneficial when you need to maintain immutability.
Alternative Methods
Using Array.prototype.concat()
The concat() method can be used to create a new array with prepended elements:
let theArray = [23, 45, 12, 67];
let response = 34;
// Single element
let newArray = [response].concat(theArray);
console.log(newArray); // [34, 23, 45, 12, 67]
// Multiple elements
let anotherArray = [1, 2, 3].concat(theArray);
console.log(anotherArray); // [1, 2, 3, 23, 45, 12, 67]
Manual Array Construction
Your current approach works but is unnecessarily verbose. Here’s a more concise version:
let theArray = [23, 45, 12, 67];
let response = 34;
// More concise than your current implementation
let newArray = [response, ...theArray];
theArray = newArray;
Performance Comparison
Here’s a comparison of different methods for adding elements to array beginning:
| Method | Time Complexity | Space Complexity | Modifies Original | Browser Support |
|---|---|---|---|---|
unshift() |
O(n) | O(1) | ✅ | All browsers |
Spread operator [...a, b] |
O(n) | O(n) | ❌ | Modern browsers |
concat() |
O(n) | O(n) | ❌ | All browsers |
| Manual loop | O(n) | O(n) | ❌ | All browsers |
According to performance tests across different JavaScript engines (V8, SpiderMonkey, JavaScriptCore), unshift() is consistently the fastest for in-place modifications, while the spread operator offers better readability and immutability benefits.
Best Practices
When to Use unshift()
- Prefer
unshift()when you need to modify the array in-place and performance is critical - Use it for single element additions where simplicity matters more than immutability
- Choose it for memory-sensitive applications since it doesn’t create new arrays
When to Use Spread Operator
- Use spread operator when working with modern JavaScript (ES6+)
- Prefer it when immutability is required (React, Redux, functional programming)
- Choose it for better code readability and maintainability
- Use it when working with multiple elements to add
Performance Considerations
// Performance test: Adding 1000 elements to beginning
const largeArray = Array.from({length: 10000}, (_, i) => i);
// unshift() - Fastest for in-place
console.time('unshift');
for (let i = 0; i < 1000; i++) {
largeArray.unshift(i);
}
console.timeEnd('unshift');
// Spread operator - Clean but creates new arrays
let arrCopy = [...largeArray];
console.time('spread');
for (let i = 0; i < 1000; i++) {
arrCopy = [i, ...arrCopy];
}
console.timeEnd('spread');
Browser Compatibility
unshift()- Supported in all browsers since IE5.5- Spread operator
[...array]- Supported in modern browsers (Chrome, Firefox, Safari, Edge), not in IE11 concat()- Supported in all browsers
For legacy browser support, unshift() or concat() are your best options.
Immutable Alternatives
If you’re working with immutable data patterns (common in React, Redux, etc.), consider these approaches:
Using Array.prototype.unshift() with Copy
// Create new array while using unshift internally
function prependImmutable(array, ...elements) {
const newArray = [...array];
newArray.unshift(...elements);
return newArray;
}
const theArray = [23, 45, 12, 67];
const newArray = prependImmutable(theArray, 34);
console.log(theArray); // [23, 45, 12, 67] (unchanged)
console.log(newArray); // [34, 23, 45, 12, 67]
Using Functional Programming Libraries
Libraries like Lodash or Ramda provide optimized immutable array operations:
// Using Lodash
import { prepend } from 'lodash/fp';
const theArray = [23, 45, 12, 67];
const newArray = prepend(34, theArray);
Performance Optimization for Large Arrays
For very large arrays where performance is critical, consider:
// Batch multiple prepends for better performance
function batchPrepend(array, elements) {
const newArray = [...elements, ...array];
return newArray;
}
// Usage
const theArray = [23, 45, 12, 67];
const elements = [34, 35, 36];
const newArray = batchPrepend(theArray, elements);
Conclusion
For adding elements to the beginning of a JavaScript array, unshift() is the most efficient built-in method with O(n) complexity that’s optimized by JavaScript engines. For modern development with ES6+, the spread operator [newElement, ...array] provides cleaner syntax while maintaining similar performance. Your current implementation works but is unnecessarily verbose - simply use array.unshift(element) for in-place modifications or [element, ...array] for immutable operations. Choose unshift() when performance is critical and you need to modify the original array, or use the spread operator when immutability and readability are more important considerations.