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: Get the final element from arrayInput Array1234Last ElementEmpty Array[]Return -1If array has elements: return arr[length-1]If array is empty: return -1
Understanding the Visualization
1
Input Array
Given array with elements to process
2
Find Last
Locate the last element using array length
3
Return Result
Return last element or -1 if empty
Key Takeaway
🎯 Key Insight: Use array length to directly access the last element in O(1) time
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