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

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

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.