DEV Community

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

Posted on

4 2

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

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more