JavaScript Snippet

Safely Read the Last Element

Difficulty: Easy

Reading `array[array.length - 1]` is the line every JavaScript developer writes a thousand times, and a chunk of those calls hide bugs on empty arrays or computed expressions. Modern `Array.prototype.at(-1)` makes the intent obvious and supports negative indexes natively. This snippet shows the modern form, the safe-default helper for empty inputs, and the typed-array story so you pick the right tool.

Code Snippets
/

Safely Read the Last Element

Safely Read the Last Element

Reading `array[array.length - 1]` is the line every JavaScript developer writes a thousand times, and a chunk of those calls hide bugs on empty arrays or computed expressions. Modern `Array.prototype.at(-1)` makes the intent obvious and supports negative indexes natively. This snippet shows the modern form, the safe-default helper for empty inputs, and the typed-array story so you pick the right tool.

JavaScript
Easy
3 snippets
arrays
utility
cheat-sheet

522 views

13

Array.prototype.at(index) accepts negative indexes that count from the end, which is the cleaner spelling of the classic array[array.length - 1]. It is supported on every evergreen runtime (Node 16.6+, all modern browsers). The savings get bigger when the array is the result of a computed expression: getRows().at(-1) runs the call once, while getRows()[getRows().length - 1] runs it twice and breaks if the function is non-idempotent. It also reads as plain English, which matters more than micro-optimisation.