Introduction
When working with arrays in JavaScript, you often need to manipulate their contents by adding or removing elements. One common requirement is to prepend new elements at the start of an array. This tutorial will explore several methods for achieving this, focusing on built-in JavaScript functions and ES6 features.
Using unshift
The most straightforward way to add one or more elements to the beginning of an array in JavaScript is by using the Array.prototype.unshift()
method. It works similarly to push
, but instead of adding elements at the end, it adds them at the start.
Example
let arr = [23, 45, 12, 67];
arr.unshift(34);
console.log(arr); // Output: [34, 23, 45, 12, 67]
The unshift
method mutates the original array and returns the new length of the array. This makes it efficient for in-place modifications.
Using ES6 Spread Operator
With ECMAScript 2015 (ES6), a more functional approach to adding elements at the start of an array can be achieved using the spread operator (...
). This method creates a new array, leaving the original unaltered.
Example
let arr = [23, 45, 12, 67];
arr = [34, ...arr]; // Creates a new array with 34 at the beginning
console.log(arr); // Output: [34, 23, 45, 12, 67]
This approach is particularly useful in scenarios where immutability is preferred.
Using concat
Method
The Array.prototype.concat()
method can also be used to prepend elements. It combines multiple arrays or values into a new array without modifying the original ones.
Example
let arr = [23, 45, 12, 67];
let newArr = [34].concat(arr);
console.log(newArr); // Output: [34, 23, 45, 12, 67]
concat
can take multiple arguments, and it automatically wraps non-array values into single-element arrays.
Performance Considerations
While unshift
directly modifies the original array, both the spread operator and concat
return new arrays. In performance-critical applications, consider:
- Mutability: Use
unshift
if you want to alter the existing array. - Immutability: Prefer the spread operator or
concat
when immutability is important.
You can refer to benchmark tests available online (e.g., jsPerf) for detailed performance comparisons between these methods under various conditions.
Summary
Adding elements at the start of an array in JavaScript can be achieved using several approaches, each with its own benefits:
unshift
: Efficient for in-place modifications.- Spread Operator (
...
): Ideal for functional programming and immutability. concat
: Useful for combining arrays without altering originals.
Choose the method that best fits your needs based on whether you require mutability, performance considerations, or code readability.