Categories
JavaScript Answers

How to get the second to last item of an array with JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *