get last item in array js

Get Last Item in Array JS

As a web developer, I have come across situations where I need to retrieve the last element from an array in JavaScript. Here are a few ways to do it:

Using Array.length property

One way to get the last element of an array in JavaScript is by using the length property. We can subtract 1 from the length of the array to get the index of the last element.


let arr = [10, 20, 30, 40, 50];
let lastElement = arr[arr.length - 1];
console.log(lastElement); //Output: 50

Using Array.slice method

Another way to get the last element of an array is by using the slice method. We can pass -1 as an argument to slice method to extract the last element of an array.


let arr = [10, 20, 30, 40, 50];
let lastElement = arr.slice(-1)[0];
console.log(lastElement); //Output: 50

Using Destructuring Assignment

We can also use destructuring assignment to retrieve the last element of an array in JavaScript.


let arr = [10, 20, 30, 40, 50];
let [lastElement] = [...arr].reverse();
console.log(lastElement); //Output: 50

In the above example, we have used the reverse method to reverse the array and then used destructuring assignment to extract the first element of the reversed array, which is the last element of the original array.

These are some of the ways to get the last element of an array in JavaScript. Choose the one that suits your requirement and use it in your code.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe