JS Built-ins
← Array33 / 226
ArrayArray.prototype.atbeginner

Array.prototype.at() β€” get last element

πŸ“– Usage Example
const nums = [10, 20, 30, 40]
nums.at(-1)  // β†’ 40  (last)
nums.at(-2)  // β†’ 30  (second-to-last)

Use at(-1) to reliably access the last element without knowing the array length.

Array.prototype.at() β€” negative indices

One of the key advantages of .at() over bracket notation is support for negative indices. arr.at(-1) returns the last element without needing arr[arr.length - 1].

Challenge: Implement getLast(arr) that returns the last element using .at(-1).

getLast([1, 2, 3]) // β†’ 3
getLast(['x'])     // β†’ 'x'
πŸ’‘ Hints (2)
  • β€’ `arr.at(-1)` is the clean equivalent of `arr[arr.length - 1]`.
  • β€’ Negative indices count backwards from the end of the array.