unshift()
ES3+Adds one or more elements to the beginning of an array and returns the new length.
Syntax
array.unshift(element1, element2, ...)Parameters
elements any Elements to add to the front of the array
Return Value
The new length of the array
Examples
const fruits = ['banana', 'cherry'];
fruits.unshift('apple');
console.log(fruits); 📌 When to Use
Use unshift() when you need to add elements to the beginning of an array. Common uses include adding new items to the top of a list, prepending data, or implementing certain queue patterns.
⚠️ Common Mistakes
Using unshift() in performance-critical code - it's O(n), use push() at the end when possible
Expecting unshift() to return the modified array - it returns the new length
Using unshift() in React/Vue state directly - use spread: [newItem, ...state]
✅ Best Practices
For immutable operations, use spread: const newArr = [newItem, ...arr]
Consider reversing your data structure if unshift() is called frequently
Use unshift with spread to add multiple items: arr.unshift(...items)
⚡ Performance Notes
unshift() is O(n) because all existing elements must be shifted to higher indices. For frequent additions to the beginning, consider using push() and reversing when needed, or use a different data structure like a linked list.
🌍 Real World Example
Adding New Notifications to the Top
Add new notifications to the beginning of a list so newest appears first
const notifications = [
{id: 1, message: 'Welcome!', time: '10:00'},
{id: 2, message: 'You have mail', time: '10:05'}
];
function addNotification(message) {
const newNotification = {
id: Date.now(),
message,
time: new Date().toLocaleTimeString()
};
// Add to beginning (newest first)
notifications.unshift(newNotification);
// Keep only last 50 notifications
if (notifications.length > 50) {
notifications.pop();
}
}