JavaScript Tutorials

JavaScript Array shift()
Syntax & Examples

Array.shift() method

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


Syntax of Array.shift()

The syntax of Array.shift() method is:

shift()

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

Return Type

Array.shift() returns value of type Any.



✐ Examples

1 Using shift() method to remove and return the first element

In JavaScript, we can use the shift() method to remove and return the first element from an array.

For example,

  1. We define an array variable arr with elements [1, 2, 3, 4, 5].
  2. We use the shift() method on arr to remove and return the first element.
  3. The first element, which is 1, is removed from arr and stored in the variable removedElement.
  4. We log removedElement to the console using console.log() method.

JavaScript Program

const arr = [1, 2, 3, 4, 5];
const removedElement = arr.shift();
console.log(removedElement);

Output

1

2 Using shift() method on an empty array

If the array is empty, shift() method returns undefined.

For example,

  1. We define an empty array variable emptyArr.
  2. We use the shift() method on emptyArr.
  3. The shift() method returns undefined as the array is empty.
  4. We log the return value to the console using console.log() method.

JavaScript Program

const emptyArr = [];
const result = emptyArr.shift();
console.log(result);

Output

undefined

Summary

In this JavaScript tutorial, we learned about shift() method of Array: the syntax and few working examples with output and detailed explanation for each example.