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:

Download  Run Code

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:

Download  Run Code

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

Download  Run Code

⮚ ES6 Spread operator

Download  Run Code

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.

Download Code

5. Using jQuery

With jQuery, you can pass index -1 to .get(index) to get the last element.

That’s all about getting the last item in an array in JavaScript.