This article is the eleventh of the Array Method Series. In this article, I will explain what the pop Array method is.
What is the Pop Method?
The pop method of arrays pops out the last item in an array.
This method returns the popped-out item and also modifies the array--removing the item from the array.
Syntax of the Pop Method
array.pop()
Without the Pop Method
Here's how to imitate the pop method:
const array = [1, 2, 3, 4, 5]
const poppedValue = array[array.length - 1]
array.length = array.length - 1
console.log(poppedValue)
// 5
console.log(array)
// [1, 2, 3, 4]
This approach is similar to what the pop method does in the background. It returns the last element and removes it from the array, making the array lesser in length by 1.
With the Pop Method
Here's how you achieve the previous result with pop:
const array = [1, 2, 3, 4, 5]
const poppedValue = array.pop()
console.log(poppedValue)
// 5
console.log(array)
// [1, 2, 3, 4]
On the contrary to how pop works, read on shift - for removing the first item from an array
Top comments (0)