How to get the last element of an array in JavaScript
Accessing the last element of arrays is essential for retrieving the most recent item, implementing stack operations, and getting final values in data processing within JavaScript applications.
With over 25 years of experience in software development and as the creator of CoreUI, I’ve accessed last elements extensively in components like activity feeds, pagination controls, and timeline displays where the final item often represents the current state or latest entry.
From my extensive expertise, the most reliable and universally supported approach is using array index notation with array.length - 1
to access the final position.
This method is dependable, works across all JavaScript versions, and clearly expresses the intent to access the last element.
Use array index notation with length - 1
to access the last element of an array.
const fruits = ['apple', 'banana', 'orange']
const lastFruit = fruits[fruits.length - 1]
// Result: 'orange'
The expression fruits.length - 1
calculates the index of the last element because arrays are zero-indexed but length counts from 1. In this example, the array has 3 elements, so fruits.length
is 3, and fruits.length - 1
equals 2, which is the index of 'orange'
. This method returns undefined
if the array is empty because array.length - 1
becomes -1, which doesn’t exist. The approach works consistently regardless of the array’s data type or size.
Best Practice Note:
This is the same approach we use in CoreUI components for accessing the current page in pagination and displaying the most recent activity in timeline components.
For modern environments, consider array.at(-1)
which provides cleaner syntax for negative indexing. Always check array length before accessing: array.length > 0 ? array[array.length - 1] : null
to handle empty arrays safely.