The shift() method is used to remove the first element from an array.

  • Removes the first element (index 0) of an array
  • Modifies the original array
  • Returns the removed element
  • Re-indexes all remaining elements → slower than pop()

1.Syntax

array.shift();

2.Basic Example

let fruits = ["Apple", "Banana", "Mango"];

let removed = fruits.shift();

console.log(removed); // Apple
console.log(fruits);  // ["Banana", "Mango"]

3.Return Value of shift()

let numbers = [10, 20, 30];

console.log(numbers.shift()); // 10

console.log(numbers); // [20, 30]

4.shift() on an Empty Array

let arr = [];

console.log(arr.shift()); // undefined

⚠ No error occurs.

5.Using shift() in a Loop

let queue = ["A", "B", "C"];

while (queue.length > 0) {
console.log(queue.shift());
}

Output

A
B
C

Categorized in:

Javascript Array Methods,