DEV Community

Cover image for Array.shift() - for shifting the first item in an array
Dillion Megida
Dillion Megida

Posted on

Array.shift() - for shifting the first item in an array

Article number 12 of the Array Method Series. In this article, I will explain the shift Array method.

What is the Shift Method?

The shift method of arrays shifts the first item out of an array.

This method returns the shifted item and also modifies the array--removing the item from the array.

Syntax of the Shift Method

array.shift()
Enter fullscreen mode Exit fullscreen mode

Without the Shift Method

Here's how to imitate the shift method:

let array = [1, 2, 3, 4, 5]

const shiftedValue = array[0]
const [, ...rest] = array
array = rest

console.log(shiftedValue)
// 1

console.log(array)
// [2, 3, 4, 5]
Enter fullscreen mode Exit fullscreen mode

This approach is similar to what the shift method does in the background. It returns the first item and removes it from the array, thereby making the array lesser in length by 1.

With the Shift Method

Here's how you achieve the previous result with shift:

const array = [1, 2, 3, 4, 5]

const shiftedValue = array.shift()

console.log(shiftedValue)
// 1

console.log(array)
// [2, 3, 4, 5]
Enter fullscreen mode Exit fullscreen mode

On the contrary to how shift works, read on pop - for removing the last item from an array

Latest comments (0)