How to get last element of an array in JavaScript?

By

Learn how to get the last element of a JavaScript array with at(-1), plus the array.length - 1 alternative for older environments.

~~~

Are you wondering how to get last element of an array in JavaScript?

Suppose you have an array, like this:

const colors = ['red', 'yellow', 'green', 'blue']

In this case the array has 4 items.

You know you can get the first item using colors[0], the second using colors[1] and so on.

The clearest modern solution is at(-1):

const lastItem = colors.at(-1)

A negative index counts from the end of the array. -1 means the last item, -2 means the second-to-last item, and so on.

If you need to support an older JavaScript environment, use the array length:

const lastItem = colors[colors.length - 1]

Both versions return undefined when the array is empty.

Tagged: JavaScript ยท All topics
~~~

Related posts about js: