Article number 12 of the Array Method Series. In this article, I will explain the
shift Array method.
What is the Shift Method?
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
Without the Shift Method
Here's how to imitate the
let array = [1, 2, 3, 4, 5] const shiftedValue = array const [, ...rest] = array array = rest console.log(shiftedValue) // 1 console.log(array) // [2, 3, 4, 5]
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
const array = [1, 2, 3, 4, 5] const shiftedValue = array.shift() console.log(shiftedValue) // 1 console.log(array) // [2, 3, 4, 5]
On the contrary to how
shift works, read on pop - for removing the last item from an array
Top comments (0)