Encodera

Thanks for reading!

Donate to the site — we work hard for you.

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:

c

Using 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:

c

The last few

slice() with a negative argument returns the last few elements:

console.log([1, 2, 3, 4, 5].slice(-2).join(', '));

Output:

4, 5

Common 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
c

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.