Skip to content
the poor coder

get last item in array js

Poor Man
Published
Reading time
1 min read
On this page

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.

Text

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.

Text

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.

Text

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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC