DEV Community

subbiah chandru
subbiah chandru

Posted on

Array.at()

The at() method takes an integer value and returns the item at that index, allowing for positive and negative integers. Negative integers count back from the last item in the array.

EX:

  1. To get last element in array we always do array\[array.length -1\] instead we could simple call array.at(-1)
  2. array\[array.length -2\] → array.at(-2)
// Our array with items
const numbers = [1, 2, 3];

// Using length property
const lengthWay = numbers[numbers.length-2];
console.log(lengthWay); // Logs: 2

// Using at() method
const atWay = colors.at(-2);
console.log(atWay); // Logs: 2
Enter fullscreen mode Exit fullscreen mode

Top comments (0)