Get the Second to Last Element in Array in JavaScript

avatar

Borislav Hadzhiev

Thu Nov 04 20212 min read

banner

Photo by Ben White

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 - 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 - 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
The at() method is not supported in Internet Explorer. If you have to support the browser, use bracket notation instead.

My personal preference is to use the bracket notation approach, even though the at() method has native support for negative indexes. This is because I haven't seen many developers use the at method and I tend to follow the principle of least surprise when writing code.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee