Skip to main content

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

MethodWhat it doesWhere it removes/addsWhat it returnsMutates the array
push()Adds an elementat the endThe new lengthYes
pop()Removes an elementfrom the endThe removed elementYes
unshift()Adds an elementat the startThe new lengthYes
shift()Removes an elementfrom the startThe removed elementYes

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:

ActionDescription
arr.shift()Removes the first element of the array
ReturnsThe removed element
Mutates the original arrayYes
On an empty arrayReturns undefined

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.