No, we are not popping champagne or anything like that. We want to remove the last item from an array. How do we accomplish this?
There is a Javascript array method called Array.pop()
, This method removes the last element in an array and returns that element. It leaves you with a shorter array.
How do I write it?
Do you mean the syntax? If so then all you have to do is append the .pop()
method to your array like this:
const elem = arr.pop()
[arr]: This is the array in which whose last element you want to remove.
[elem]: This holds the element that is removed from the array.
Can you use show us an example of how it is being used? Yea sure.
const numArray = [1, 2, 3, 4, 5];
const elem = numArray.pop()
console.log(numArray) // [1, 2, 3, 4];
console.log(elem) // 5
As you see above, all you have to do is call the method on the array, no arguments are required. The original array is mutated.
What if the array is empty, what happens then? Let's try it out
const emptyArray = [];
const elem = emptyArray.pop()
console.log(elem) // undefined
It returns undefined because there is no element in the array.
That's cool and simple, but what if I want to remove the first element of an array?
Well, you'll have to wait till tomorrow to find out, follow me here nedyudombat to get notified when I reveal the answer tomorrow. For now, just practise more on using the Array.pop()
to remove elements from the end of an array.
That's all for today, See you next time!!! 😆 😁
Thank you for reading. 👍
Top comments (0)