This content originally appeared on DEV Community and was authored by Dillion Megida
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
This content originally appeared on DEV Community and was authored by Dillion Megida
Dillion Megida | Sciencx (2022-05-10T06:07:59+00:00) Array.pop() – for popping the last item of an array. Retrieved from https://www.scien.cx/2022/05/10/array-pop-for-popping-the-last-item-of-an-array/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.