Given an array, the task is to get the last item of an array in JavaScript. There are several ways to get the last item of an array.
1. Using Bracket Notation
Arrays in JavaScript are zero-indexed, meaning the first item is at index 0. You can use the length of the array to calculate the index of the last element.
let arr = [10, 20, 30, 40, 50]; let lastItem = arr[arr.length - 1]; console.log(lastItem); // Output: 50
2. Using slice() Method
The slice()
method can extract a portion of an array. By providing -1
as the argument, it retrieves the last element as a new array.
let arr = [10, 20, 30, 40, 50]; let lastItem = arr.slice(-1)[0]; console.log(lastItem); // Output: 50
3. Using at() Method (ES2022)
The at()
method allows you to access elements using positive or negative indices. To get the last item, you can use -1
as the index.
let arr = [10, 20, 30, 40, 50]; let lastItem = arr.at(-1); console.log(lastItem); // Output: 50
4. Using pop() Method
The pop()
method removes and returns the last item of an array. This is destructive and changes the original array.
let arr = [10, 20, 30, 40, 50]; let lastItem = arr.pop(); console.log(lastItem); // Output: 50 console.log(arr); // Output: [10, 20, 30, 40]
5. Using a for Loop
For scenarios where you want to retrieve the last item manually, a for
loop can be used. While not the most efficient, it demonstrates how to iterate through an array.
let arr = [10, 20, 30, 40, 50]; let lastItem; for (let i = 0; i < arr.length; i++) { if (i === arr.length - 1) { lastItem = arr[i]; } } console.log(lastItem); // Output: 50
6. Using reduce()
Method
The reduce()
method can be used to iterate over the array and return the last item.
let arr = [10, 20, 30, 40, 50]; let lastItem = arr.reduce((_, current) => current); console.log(lastItem); // Output: 50
7. Using length and Destructuring (ES6)
Destructuring assignment combined with the length
property can be used to get the last item in a concise manner.
let arr = [10, 20, 30, 40, 50]; let [lastItem] = [arr[arr.length - 1]]; console.log(lastItem); // Output: 50