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

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

πŸ“– Usage Example
const arr = ['x', 'y', 'z']
arr[arr.length - 1]  // β†’ 'z'  (bracket)
arr.at(-1)           // β†’ 'z'  (at β€” cleaner)

Prefer at() over bracket notation when accessing the last element β€” it avoids manual length arithmetic.

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

.at() can accept computed indices just like bracket notation. For an odd-length array, the middle element is at index Math.floor(arr.length / 2).

Challenge: Implement getMiddle(arr) that returns the middle element of an odd-length array using .at().

getMiddle([1, 2, 3, 4, 5]) // β†’ 3
getMiddle([10, 20, 30])    // β†’ 20
πŸ’‘ Hints (2)
  • β€’ `Math.floor(arr.length / 2)` gives the center index for any odd-length array.
  • β€’ `.at()` accepts any integer expression as an argument.