Get the Second to Last Element in Array in JavaScript

avatar

Borislav Hadzhiev

Last updated: Aug 29, 2022

banner

Photo from Unsplash

Get the Second to Last Element in Array #

To get the second to last element in an array, use bracket notation to access the array at index array.length - 2, e.g. arr[arr.length - 2]. The last element in an array has an index of array.length - 1 and the second to last an index of array.length - 2.

index.js
const arr = ['a', 'b', 'c', 'd']; const secondToLast = arr[arr.length - 2]; console.log(secondToLast); // 👉️ "c"

We accessed the array at index array.length - 2 to get the second to last array element.

Indexes are zero-based in JavaScript, meaning the first element in the array has an index of 0 and the last an index of array.length - 1.

By subtracting 1 from the last index, we get the index of the second to last array element.

If the array contains only a single element or is empty, we would get an undefined value back.

index.js
const arr = []; const secondToLast = arr[arr.length - 2]; console.log(secondToLast); // 👉️ undefined

An alternative approach is to use the Array.at method.

To get the second to last element in an array, call the at() method on the array, passing it -2 as a parameter, e.g. arr.at(-2). The at method returns the array element at the specified index. When passed a negative index, the at() method counts back from the last item in the array.

index.js
const arr = ['a', 'b', 'c', 'd']; const secondToLast = arr.at(-2); console.log(secondToLast); // 👉️ "c"

The only parameter the at() method takes is the index of the element we want to get.

When a negative index is passed to the method, it starts counting back from the end of the array. For example -1 gets us the last element, -2 the second to last, etc.

If the array contains only a single element or is empty, we would get undefined back.

index.js
const arr = []; const secondToLast = arr.at(-2); console.log(secondToLast); // 👉️ undefined

Which approach you pick is a matter of personal preference. The Array.at() method is quite convenient for this use case because it supports negative indexing.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.