31 January 2024

This snippet explains how to get last item of an array. The example retrieves the last item of the array by determining its index through subtracting one from the array's length. This approach leverages the fact that array indices start from 0, making the last element's index equal to the array length minus one.

Source code viewer
  1. const myArray = [1, 2, 3, 4, 5];
  2. const lastItem = myArray[myArray.length - 1];
  3.  
  4. console.log(lastItem);
Programming Language: ECMAScript