What does shift() do?
The shift() method in JavaScript is the "reverse sibling" of unshift().
It removes the first element of the array and returns its value.
Example:
javascript
const fruits = ["apple", "banana", "cherry"];
const first = fruits.shift();
console.log(first); // "apple" - the removed element
console.log(fruits); // ["banana", "cherry"]- Removes the first element (
index = 0), - Shifts all remaining elements to the left,
- Mutates the original array,
- Returns the removed value.
Example with an empty array:
javascript
const arr = [];
const removed = arr.shift();
console.log(removed); // undefined
console.log(arr); // []If the array is empty, it returns undefined, but there is no error.
Comparison with other methods
| Method | What it does | Where it removes/adds | What it returns | Mutates the array |
|---|---|---|---|---|
push() | Adds an element | at the end | The new length | Yes |
pop() | Removes an element | from the end | The removed element | Yes |
unshift() | Adds an element | at the start | The new length | Yes |
shift() | Removes an element | from the start | The removed element | Yes |
Usage example:
javascript
const queue = [];
queue.push("A");
queue.push("B");
queue.push("C");
console.log(queue.shift()); // "A"
console.log(queue.shift()); // "B"
console.log(queue); // ["C"]This is a common way to implement a queue - a "first in, first out" (FIFO) data structure.
In short:
| Action | Description |
|---|---|
arr.shift() | Removes the first element of the array |
| Returns | The removed element |
| Mutates the original array | Yes |
| On an empty array | Returns undefined |
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.