Get last item in an array in JavaScript
This post will discuss how to get the last element of an array in JavaScript.
1. Using [] operator
The recommended solution to get any element of an array is using the [] operator. To get the last element, simply pass its index to the [] operator, as shown below:
|
1 2 3 4 5 6 7 |
const arr = [ 5, 3, 2, 7, 8 ]; const last = arr[arr.length-1]; console.log(last); /* Output: 8 */ |
2. Using Destructuring Assignment
Another good solution is to use the Destructuring Assignment syntax to retrieve the last element of an array. The following code example demonstrates its usage:
|
1 2 3 4 5 6 7 8 |
const arr = [ 5, 3, 2, 7, 8 ]; const [last] = arr.slice(-1); console.log(last); /* Output: 8 */ |
3. Using Array.prototype.pop() function
The pop() method returns the last element from an array but removes it from the array as well. To avoid modifying the original array, consider creating the copy of the array before calling the pop() method. You can do this in two ways:
⮚ Slicing
|
1 2 3 4 5 6 7 8 |
const arr = [ 5, 3, 2, 7, 8 ]; const last = arr.slice(-1).pop(); console.log(last); /* Output: 8 */ |
⮚ ES6 Spread operator
|
1 2 3 4 5 6 7 8 |
const arr = [ 5, 3, 2, 7, 8 ]; const last = [...arr].pop(); // not recommended for large arrays console.log(last); /* Output: 8 */ |
4. Using Underscore/Lodash Library
Alternatively, with the Underscore, or Lodash JavaScript library, you can use the no-arg _.last method, which returns the last element of an array.
|
1 2 3 4 5 6 7 8 9 |
const _ = require('underscore'); const arr = [ 5, 3, 2, 7, 8 ]; const last = _.last(arr); console.log(last); /* Output: 8 */ |
5. Using jQuery
With jQuery, you can pass index -1 to .get(index) to get the last element.
|
1 2 3 4 5 6 7 8 |
const arr = [ 5, 3, 2, 7, 8 ]; const last = $(arr).get(-1); console.log(last); /* Output: 8 */ |
That’s all about getting the last item in an array in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)