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:
- To get last element in array we always do
array\[array.length -1\]
instead we could simple callarray.at(-1)
-
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
Top comments (0)