How to Remove the Last Element in a JavaScript Array and Return It?

Get and remove the last item in a JavaScript array

The JavaScript Array.prototype.pop() method removes the last element from an array and returns the removed value. It mutates the original array, which means that the contents of the array are modified and its length is changed. For example:

const arr = [ 1, 2, 3, 4 ];
const lastElem = arr.pop();

console.log(lastElem); // 4
console.log(arr); // [1, 2, 3]
console.log(arr.length); // 3

If the Array.prototype.pop() method is called on an empty array, it would return undefined:

const arr = [];
const lastElem = arr.pop();

console.log(lastElem); // undefined

Hope you found this post useful. It was published . Please show your love and support by sharing this post.