JS Built-ins
← Array35 / 226
ArrayArray.prototype.atintermediate

Array.prototype.at() β€” out-of-bounds returns undefined

πŸ“– Usage Example
const arr = [1, 2, 3]
arr.at(5)   // β†’ undefined
arr.at(-5)  // β†’ undefined

at() returns undefined when the index is out of bounds, making it safe for optional access.

Array.prototype.at() β€” safe access

.at(n) returns undefined when n is out of bounds (either too large or too negative). This makes it a safe alternative to bracket notation.

Challenge: Implement safeAt(arr, n) that returns arr.at(n), which is undefined if the index is out of bounds.

safeAt([1, 2, 3], 10)  // β†’ undefined
safeAt([1, 2, 3], -5)  // β†’ undefined
safeAt([1, 2, 3], 1)   // β†’ 2
πŸ’‘ Hints (2)
  • β€’ `.at()` never throws β€” it returns `undefined` when the index is out of range.
  • β€’ A negative index `-n` is out of bounds when `n > arr.length`.