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

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

πŸ“– Usage Example
const colors = ['red', 'green', 'blue']
colors.at(0)  // β†’ 'red'
colors.at(1)  // β†’ 'green'

Use at() to access an element by a positive index, just like bracket notation.

Array.prototype.at()

Array.prototype.at(index) returns the element at the given index. It works just like bracket notation for positive indices, but also accepts negative integers to count from the end.

Challenge: Implement getElement(arr, 0) that returns the first element of arr using .at(0).

getElement([10, 20, 30], 0) // β†’ 10
getElement(['a', 'b'], 0)   // β†’ 'a'
πŸ’‘ Hints (2)
  • β€’ `arr.at(0)` is equivalent to `arr[0]` for non-negative indices.
  • β€’ The `.at()` method returns `undefined` for out-of-bounds indices, just like bracket notation.