Loading article...
The pop() method removes the last element from an array and returns that element.
Array.prototype.customPop = function () { if (this.length === 0) return undefined; // Return undefined if the array is empty const lastElement = this[this.length - 1]; // Store the last element this.length = this.length - 1; // Decrease the length of the array return lastElement; // Return the removed element }; // Example usage: const array = [1, 2, 3]; const popped = array.customPop(); console.log(popped); // Output: 3 console.log(array); // Output: [1, 2] console.log([].customPop()); // Output: undefined (empty array case)
this.length === 0, it returns undefined, just like pop().this[this.length - 1] before modifying the array.1, effectively removing the last element.pop() behavior by returning the removed item.✔ Works on normal arrays
✔ Works on empty arrays ([].customPop() → undefined)
✔ Modifies the original array in place
✔ Returns the last element as expected
This implementation is clean, efficient, and follows Array.prototype.pop exactly.
Test your understanding with 3 quick questions