How do you get the last element of an array in JavaScript?
Short answer: use at(-1). It counts from the end of the array and works in every modern browser and in Node.js 16.6 or newer. The classic way, which works everywhere, is arr[arr.length - 1].
const fruits = ["apple", "banana", "cherry"];
console.log(fruits.at(-1)); // cherry
console.log(fruits[fruits.length - 1]); // cherryNeither of them changes the array. If the array is empty, both return undefined.
at(-1) and length - 1 read the last element, fruits[-1] does not work in JavaScript and pop() removes the element as it returns it.
Every way to get the last element
| Method | Example | Changes the array? | Empty array |
|---|---|---|---|
at(-1) | fruits.at(-1) | No | undefined |
length - 1 | fruits[fruits.length - 1] | No | undefined |
slice(-1) | fruits.slice(-1)[0] | No | undefined |
pop() | fruits.pop() | Yes, removes it | undefined |
findLast() | nums.findLast(n => n > 10) | No | undefined |
For everyday code, use at(-1). Use pop() only when you also want to remove the element.
Get the last element with at(-1)
at() accepts negative indexes: -1 is the last element, -2 the one before, and so on.
const scores = [72, 85, 91, 64];
console.log(scores.at(-1)); // 64
console.log(scores.at(-2)); // 91
console.log(scores.at(0)); // 72It also works with strings: "hello".at(-1) returns "o". at() was added in ES2022, so very old browsers such as Internet Explorer don't support it. If you must support them, use length - 1.
Get the last element with length - 1
Arrays start at index 0, so the last index is always length - 1:
const fruits = ["apple", "banana", "cherry"];
const lastIndex = fruits.length - 1; // 2
console.log(fruits[lastIndex]); // cherryWriting fruits[fruits.length] returns undefined, because index 3 doesn't exist. And fruits[-1] also returns undefined: unlike Python, square brackets in JavaScript don't count from the end.
