What is the cleanest way to get the last element of a JavaScript array?
The cleanest and most modern way to get the last element of a JavaScript array is using array.at(-1) (ES2022). Passing -1 counts backward from the end of the array and directly returns the final item—or undefined if the array is empty—without repeating the array name for length - 1.
Using .at(-1) vs. Bracket Indexing Traditional array[array.length - 1] works everywhere, but .at(-1) keeps code clean and readable, especially when chaining methods or accessing nested arrays.
JavaScript
const techs = ["HTML", "CSS", "JavaScript", "React"];
// Modern ES2022+ way (clean and readable)
const lastTech = techs.at(-1);
console.log(lastTech); // "React"
// Classic way (useful for legacy environments)
const fallbackLast = techs[techs.length - 1];
console.log(fallbackLast); // "React"
// Safely returns undefined for an empty array
console.log([].at(-1)); // undefined
You must log in or register to comment.
