TobilobaCodes – LeetCode Explorer

2619. Array Prototype Last

Enhance all JavaScript arrays by adding a last() method that returns the last element in the array. If the array is empty, return -1.

📄 Problem Statement

Add a method last() to Array.prototype so that it can be called on any array instance. The method should return:

This assumes the array is a valid result of JSON.parse.

💡 Example


[].last();           // ➞ -1
[1, 2, 3].last();    // ➞ 3
["a", "b"].last();   // ➞ "b"

🧠 Explanation

By modifying Array.prototype, we can add a custom method that becomes available to all arrays. We simply check the length of the array and return either the last element or -1 if empty.

This approach is useful when you want to extend built-in behavior cleanly, but in production code, prototype modifications should be done cautiously to avoid conflicts.

✅ Your Solution


/**
 * @return {any}
 */
Array.prototype.last = function() {
    return this.length ? this[this.length - 1] : -1;
};