array at method

ES2022, JavaScript, Array

Access array elements using positive and negative indices with the at() method.

Explanation

  • arr.at(index): Returns the element at the specified index, supporting negative indices.
  • arr.at(-1): Returns the last element of the array.
  • arr.at(-2): Returns the second-to-last element, and so on.
  • More readable than arr[arr.length - 1] for accessing elements from the end.

Usage

To access array elements with positive or negative indices:

const fruits = ['apple', 'banana', 'cherry', 'date'];

// Positive indices (same as bracket notation)
console.log(fruits.at(0)); // 'apple'
console.log(fruits.at(2)); // 'cherry'

// Negative indices (count from end)
console.log(fruits.at(-1)); // 'date' (last element)
console.log(fruits.at(-2)); // 'cherry' (second-to-last)

// Compare with traditional approach
console.log(fruits[fruits.length - 1]); // 'date' (verbose)
console.log(fruits.at(-1)); // 'date' (concise)