Add an Item to the Beginning of an Array in JavaScript
In this tutorial, we’ll learn how to insert a new item at the very beginning of the array with examples and explanation.
Method 1: Using unshift()
The unshift()
method adds one or more elements to the beginning of an array. It directly modifies the original array and returns the new length. This is the most direct and widely used approach.
const fruits = ["banana", "cherry"];
const newLength = fruits.unshift("apple");
console.log("Updated array:", fruits);
console.log("New length:", newLength);
Updated array: ["apple", "banana", "cherry"]
New length: 3
Method 2: Using Spread Operator (Immutable Approach)
If you prefer not to mutate the original array — especially useful in React and other functional programming environments — the spread operator [newItem, ...array]
is an elegant way to create a new array that starts with the new item followed by the existing values.
const fruits = ["banana", "cherry"];
const updatedFruits = ["apple", ...fruits];
console.log("Original:", fruits);
console.log("Updated:", updatedFruits);
Original: ["banana", "cherry"]
Updated: ["apple", "banana", "cherry"]
When to Use Each Method
unshift()
: Ideal when you want to update the original array directly. Simple and easy to understand.- Spread operator: Best when working in environments that prefer immutability (like Redux or React state updates).
Important Considerations
When adding items to the beginning of an array:
unshift()
modifies the array and is not suitable for use in immutable state patterns.- The spread operator is clean but creates a new array — which may matter in performance-sensitive applications.
- Always be mindful of the context: do you want to change the original or produce a new version?
Comments
Loading comments...