Array.prototype.atLoading saved progress…

Array.prototype.at

You've reached for arr[arr.length - 1] to grab the last element of an array more than once. Array.prototype.at is the modern, less noisy way to do that — it accepts negative indices that count back from the end.

Implement arrayAt(arr, index). When index is 0 or positive, return the element at that position. When index is negative, count from the end: -1 is the last element, -2 is the second-to-last, and so on. If the resolved position falls outside the array, return undefined.

Signature

function arrayAt(arr, index) {
  // returns arr[index] for index >= 0,
  // arr[arr.length + index] for index < 0,
  // or undefined if out of range.
}

Examples

arrayAt(['a', 'b', 'c', 'd'], 1);  // 'b'
arrayAt(['a', 'b', 'c', 'd'], -1); // 'd'
arrayAt(['a', 'b', 'c'], 10);   // undefined
arrayAt(['a', 'b', 'c'], -10);  // undefined
arrayAt(['a', 'b', 'c'], 1.7);  // 'b' — index truncates toward zero

Notes

  • Negative indices count from the end: -1 is the last element, not "one before index 0."
  • Out-of-range indices — positive or negative — return undefined, not throw.
  • Non-integer indices truncate toward zero (per the spec): 1.7 becomes 1, -1.9 becomes -1.
  • Empty arrays always return undefined, regardless of the index.
  • Don't mutate the array. arrayAt is a read-only lookup.
Loading editor…