How to get the last element of an array
Short answer
The at() method accepts a negative index, counted from the end:
console.log(['a', 'b', 'c'].at(-1));Output:
cUsing length
Older code reads the last element at the index one less than the length:
const items = ['a', 'b', 'c'];
console.log(items[items.length - 1]);Output:
cThe last few
slice() with a negative argument returns the last few elements:
console.log([1, 2, 3, 4, 5].slice(-2).join(', '));Output:
4, 5Common mistake
Negative indexes in square brackets do not work: items[-1] looks for a property named -1 and returns undefined:
const items = ['a', 'b', 'c'];
console.log(items[-1]);
console.log(items.at(-1));Output:
undefined
cFunctions used in this recipe
- Array.prototype.at — Returns the element at an index; negative indexes are allowed.
- Array.prototype.slice — Returns part of an array.