JavaScript Array shift()

The JavaScript Array shift() method removes the first element from an array and returns that element.

The syntax of the shift() method is:

arr.shift()

Here, arr is an array.


shift() Parameters

The shift() method does not have any parameters.


Return value from shift()

  • Removes the first element from array and returns that value.
  • Returns undefined if the array is empty.

After removing the element at the 0th index, it shifts other values to consecutive indexes down.

Notes:

  • This method changes the original array and its length.
  • To remove the last element of an array, use the JavaScript Array pop() method.

Example: Using shift() method

var languages = ["JavaScript", "Python", "Java", "C++", "Lua"];

var shifted = languages.shift();

console.log(languages); // [ 'Python', 'Java', 'C++', 'Lua' ]
console.log(shifted); // JavaScript

// shift returns any type of object
var numbers = [
  [1, 2, 3],
  [4, 5, 6],
  [-5, -4, -3],
];
console.log(numbers.shift()); // [ 1, 2, 3 ]
console.log(numbers); // [ [ 4, 5, 6 ], [ -5, -4, -3 ] ]

Output

[ 'Python', 'Java', 'C++', 'Lua' ]
JavaScript
[ 1, 2, 3 ]
[ [ 4, 5, 6 ], [ -5, -4, -3 ] ]

Recommended Readings: