.pop() and how the array is mutated

Hi. I’m going through arrays and one specific bit of code confuses me.

const newItemTracker = ['item 0', 'item 1', 'item 2'];

const removed = newItemTracker.pop();

// Output: [ 'item 0', 'item 1' ]
// Output: item 2

So here is what confuses me. When we create the constant ‘removed’ we set it to newItemTracker.pop(). Shouldn’t this mean that the popped value of newItemTracker only exists within the ‘removed’ constant and does not change the original variable? I hope this makes some sort of sense. Could someone please help?

If we check the documentation:


we see the following description:

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

which is exactly what is happening

If you simple want the last element of the array: https://stackoverflow.com/questions/9050345/selecting-last-element-in-javascript-array

1 Like

Thanks. What if I wanted only one constant to have the popped value? What I’m saying is that the newItemTracker constant would remain the same with the same values, but only the constant ‘removed’ would have the popped value?

you do? the removed variable

so you don’t want to mutate the array? Then simple use newItemTracker.length - 1 to get the last item (you could write a method for this, see the stackoverflow question I linked to)

someone made the .pop() method and designed with certain functionality in mind. If this is not what you are looking for you should: check if there is a method which suits your need or write your own


Oh ok. Makes sense now. Thanks