How to Use the JavaScript Array.at() Method to Get First, Last, and Second-Last Items

JavaScript has a built-in method called .at() which allows you to access array items in their index.

at() has a number of advantages:

  • cleaner, and easier, to read
  • does relative indexing – so no more array.length
  • supports negative numbers, to easily select from the end of the array

To use the .at() method, you first need to create an array and populate it with some values.

 For example, to create an array with some values

myArray = ["apple", "orange", "banana", "kiwi", "mango"];

To use the .at() method to get the first item in the array

firstItem = myArray.at(0);
// Output: "apple"

To use the .at() method to get the last item in the array

lastItem = myArray.at(myArray.length - 1);
// Output: "mango"

To use the .at() method to get the second-last item in the array

secondLastItem = myArray.at(myArray.length - 2);
// Output: "kiwi"

Remember that the .at() method will return undefined if the index you provide is out of bounds, so make sure to check the length of the array before trying to access items at the end of the array.

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at