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