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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code