Sometimes, we want to get the second to last item of an array with JavaScript.
In this article, we’ll look at how to get the second to last item of an array with JavaScript.
How to get the second to last item of an array with JavaScript?
To get the second to last item of an array with JavaScript, we use the array at
method.
For instance, we write
const arr = [1, 2, 3, 4];
const secondLast = arr.at(-2);
to call arr.at
with -2 to return the 2nd last item of the arr
array.
Therefore, secondLast
is 3.
Conclusion
To get the second to last item of an array with JavaScript, we use the array at
method.