How to Use the JavaScript 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 =;
// Output: "apple"

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

lastItem = - 1);
// Output: "mango"

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

secondLastItem = - 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.