Array Prototype Last - Problem

Write code that enhances all arrays such that you can call the array.last() method on any array and it will return the last element. If there are no elements in the array, it should return -1.

You may assume the array is the output of JSON.parse.

Note: This problem requires extending JavaScript's Array prototype with a custom method.

Input & Output

Example 1 — Basic Array
$ Input: arr = [1, 2, 3, 4, 5]
Output: 5
💡 Note: The array has 5 elements, so the last element at index 4 is 5
Example 2 — Single Element
$ Input: arr = [10]
Output: 10
💡 Note: Array with one element - the first and last element are the same
Example 3 — Empty Array
$ Input: arr = []
Output: -1
💡 Note: Empty array has no elements, so return -1 as specified

Constraints

  • 0 ≤ arr.length ≤ 1000
  • -1000 ≤ arr[i] ≤ 1000

Visualization

Tap to expand
Array Prototype Last INPUT Array Structure: 1 [0] 2 [1] 3 [2] 4 [3] 5 [4] Input Values: arr = [1, 2, 3, 4, 5] length = 5 Last element is highlighted ALGORITHM STEPS 1 Extend Prototype Add last() to Array.prototype 2 Check Length If length == 0, return -1 3 Calculate Index lastIndex = length - 1 4 Return Element return this[lastIndex] Array.prototype.last = function() { if(!this.length) return -1; return this[this.length-1]; } FINAL RESULT Accessing last element: 1 2 3 4 5 this[4] Output: 5 Status: OK Last element returned Key Insight: Direct Index Access - Use this[this.length - 1] for O(1) time complexity. The prototype method extends ALL arrays, enabling arr.last() syntax. Handle empty arrays with -1 return. TutorialsPoint - Array Prototype Last | Direct Index Access
Asked in
Google 25 Amazon 20 Facebook 15
32.9K Views
Medium Frequency
~5 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen