Mastering the unshift() Method in JavaScript
Introduction
The unshift() method in JavaScript is used to add one or more elements to the beginning of an array. It shifts the existing elements to higher indexes and returns the new length of the array. 🧠
📌 What is unshift()?
unshift() modifies the original array by inserting new elements at index 0.
- 📦 Works only with arrays.
- ➕ Adds elements to the start of the array.
- 🔄 Changes the original array (mutates it).
💡 Syntax
Basic Syntax
array.unshift(element1, element2, ..., elementN)🧵 Adding a Single Element to Start
Unshift Single Element
const fruits = ["Banana", "Mango"];
fruits.unshift("Apple");
console.log(fruits); // ["Apple", "Banana", "Mango"]📦 Adding Multiple Elements to Start
Unshift Multiple Elements
const numbers = [3, 4, 5];
numbers.unshift(1, 2);
console.log(numbers); // [1, 2, 3, 4, 5]📏 Return Value
The unshift() method returns the new length of the array after elements are added.
Return Value of unshift()
const colors = ["Green", "Blue"];
const newLength = colors.unshift("Red");
console.log(newLength); // 3⚠️ Important Notes
Note
unshift() changes the original array. If you need an immutable alternative, consider using the spread syntax.
Immutable Alternative
const arr = [3, 4];
const newArr = [1, 2, ...arr];
console.log(newArr); // [1, 2, 3, 4]
console.log(arr); // [3, 4]📊 Quick Reference Table
| Operation | Code | Result |
|---|---|---|
| Unshift Single | arr.unshift("X") | Adds "X" at start |
| Unshift Multiple | arr.unshift("X", "Y") | Adds both at start |
| Return Value | let len = arr.unshift("X") | Returns new length |
>>"If push() grows arrays at the end, unshift() grows them from the front — both equally important for dynamic data." 🔄
🔥 Summary
The unshift() method is perfect when you need to insert elements at the start of an array. It works hand in hand with shift() for queue-like operations in JavaScript.