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

Array.prototype.at() β€” second-to-last element

πŸ“– Usage Example
const items = ['a', 'b', 'c', 'd']
items.at(-2)  // β†’ 'c'
items.at(-1)  // β†’ 'd'

Use at() with negative indices to access elements from the end of an array.

Array.prototype.at() β€” counting from the end

.at(-2) gives you the second-to-last element. Compare this to the bracket notation equivalent: arr[arr.length - 2] β€” .at() is much more readable.

Challenge: Implement getSecondToLast(arr) that returns the second-to-last element using .at(-2).

getSecondToLast([1, 2, 3, 4]) // β†’ 3
getSecondToLast(['a', 'b'])   // β†’ 'a'
πŸ’‘ Hints (2)
  • β€’ `arr.at(-2)` counts 2 from the end, equivalent to `arr[arr.length - 2]`.
  • β€’ If the array has fewer than 2 elements, `.at(-2)` returns `undefined`.