What does unshift() do?
The unshift() method in JavaScript does the opposite of what shift() does:
it adds one or more elements to the beginning of an array
and returns the new length of the array.
Example:
javascript
const fruits = ["banana", "cherry"];
const newLength = fruits.unshift("apple");
console.log(fruits); // ["apple", "banana", "cherry"]
console.log(newLength); // 3- Elements are added to the beginning of the array (at index
0). - All existing elements shift to the right.
- The method mutates the original array.
- Returns the new length of the array, not the array itself.
You can add several elements at once:
javascript
const numbers = [3, 4];
numbers.unshift(1, 2);
console.log(numbers); // [1, 2, 3, 4]How it works
- Creates space at the beginning of the array.
- Shifts all current elements to new indices.
- Inserts the new values at positions starting from 0.
- Updates the
lengthproperty.
Comparison with other methods
| Method | What it does | Where it adds / removes | What it returns | Mutates the array |
|---|---|---|---|---|
push() | Adds an element | To the end | New length | Yes |
pop() | Removes an element | From the end | Removed element | Yes |
unshift() | Adds an element | To the beginning | New length | Yes |
shift() | Removes an element | From the beginning | Removed element | Yes |
Usage example (queue)
javascript
const queue = [];
queue.unshift("first");
queue.unshift("second");
console.log(queue); // ["second", "first"]It can be used to add elements to the front of a queue, when you need to work in a FIFO (First In - First Out) style.
Short version:
| Action | Description |
|---|---|
arr.unshift(value1, value2, ...) | Adds element(s) to the beginning |
| Returns | The new length of the array |
| Mutates the array | Yes |
| Example | [2, 3].unshift(1) -> [1, 2, 3] |
Conclusion:
unshift()is a method for adding elements to the beginning of an array, with automatic shifting of all indices and an updated length.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.