JavaScript Array.shift() Method

MD Niaz Rahman Khan Jan 30, 2023
  1. Syntax of JavaScript Array.shift() Method
  2. Example Codes: Use the Array.shift() Method
  3. Example Codes: Use the Array.shift() Method to an Empty Array
JavaScript Array.shift() Method

To remove the first element from an array, the Array.shift() method is used. This method directly makes changes in the original array.

Syntax of JavaScript Array.shift() Method

array.shift()

Parameters

The Array.shift() method does not accept any parameter.

Return

The removed first element from an array is returned. If the array does not contain any element, then undefined will be returned.

Example Codes: Use the Array.shift() Method

const sportsArray = ['Apple', 'Football', 'Cricket', 'Tennis', 'Hockey']
console.log('Before Using Shift: ', sportsArray)

const shiftItem = sportsArray.shift()
console.log('After Using Shift: ', sportsArray)
console.log('Shifted Item: ', shiftItem)

Output:

Before Using Shift:  [ 'Apple', 'Football', 'Cricket', 'Tennis', 'Hockey' ]
After Using Shift:  [ 'Football', 'Cricket', 'Tennis', 'Hockey' ]
Shifted Item:  Apple

The sportsArray consists of five elements at first. We used the shift() method to remove the first element from the array.

It changes the original array, and the elements of the array become four after using this method. Finally, we have printed the removed element.

Example Codes: Use the Array.shift() Method to an Empty Array

const emptyArray = []
const shiftItem = emptyArray.shift()

console.log(shiftItem)

Output:

undefined

We used the array.shift() method to an empty array. As a result, this method returned undefined.

MD Niaz Rahman Khan avatar MD Niaz Rahman Khan avatar

Niaz is a professional full-stack developer as well as a thinker, problem-solver, and writer. He loves to share his experience with his writings.

LinkedIn

Related Article - JavaScript Array