DEV Community

Discussion on: Tips: How to get last element of an array in javascipt

Collapse
 
devvsakib profile image
Sakib Ahmed

pop() method removes the last element from an array and returns that element. This method changes the length of the array.

Collapse
 
schemetastic profile image
Rodrigo Isaias Calix • Edited

Cool, i knew a little about the pop() method but now is more clear to me.

Here is a small example of this

var fruits = ['apples', 'oranges', 'grapes'];
var myLastFruit = fruits.pop();
console.log(fruits, myLastFruit);
Enter fullscreen mode Exit fullscreen mode

This would log:

Array [ "apples", "oranges" ] grapes
Enter fullscreen mode Exit fullscreen mode

As you can see 'grapes' now doesn't form part of the fruits variable but at the same time the pop() method returns the last item of the array. So clearly, if someone is going to use this method must be aware of this.

Some comments have been hidden by the post's author - find out more