We can access the JavaScript array items by their index. We will be using the index to find the last element of the JS array. Here, I shared some easiest methods to do find the last array element.
1. Using Array Length Property
We can use the array length property to get the value of the last element in the JavaScript Array.
Example
const numArray = [1, 2, 3, 4];
const lastElementIndex = numArray.length - 1;
console.log(lastElementIndex); // 3
const lastElement = numArray[lastElementIndex];
console.log(lastElement); // 4
2. Using Array Slice Method
JavaScript Array slice() method is used to slice the array and create a new array from the returning array. It is also used to find the value of the last element of the array by slicing it with the value -1.
Example
const numArray = [1, 2, 3, 4];
const lastElementArray = numArray.slice(-1); // [4] is the new array returned by slice() method
const lastElement = lastElementArray[0]; // 0 is the index of the last element
console.log(lastElement); // 4
3. Using Array Reverse Method
In this method, we will first clone the original array to the new variable and then reverse the new array. Finally, we obtain the first element of the new array using the index option. So, obviously, the first element of the new array would become the last element of the original array. This method wouldn’t change the values of the existing array. You can use this method only if you like to perform various operations on the array. The original array is kept unchanged and it is one of the safest methods.
Example
const numArray = [1, 2, 3, 4];
const reversedArray = [...numArray]; // clone the array to the new variable
reversedArray.reverse(); // reverse the elements, so it is now [4, 3, 2, 1]
const lastElement = reversedArray[0]; // get the first element of the new array
console.log(lastElement); // 4
Conclusion
The easiest method for getting the last element of the JavaScript array is the first method. If you have different requirements, you may use other methods too.