There are a number of different ways to get the last element of an array in JavaScript.
Below we will explore those techniques, each with a simple example.
The Most Common Technique Using length() -1
The simplest way to get the last element of an array in JavaScript is to subtract one from the length of the array and then use that value as the index to assign the last item to a variable.
This sounds complicated, but it’s quite easy to do.
Example:
var demoArray = ["Apple", "Ebay", Google", "Microsoft"];
var lastItem1 = demoArray[demoArray.length() - 1];
An Alternative Technique Using slice()
The second way is to use the array.slice() method to create a temporary array that contains the range of values from index negative one to index zero. To be clear, the slice starts at the last value in the array and ends at the first value of the array. This method is frowned upon as it can be hard to understand the code.
Example:
var lastItem2 = demoArray.slice(-1)[0];
pop() Can Also Be Used To Get the Last Item
The third way involves using the array.pop() method as it will return the value of the last element in the array. The side effect of this technique is that the last element of the array will be removed. Depending on the situation, that may or may not be desirable.
Example:
var lastItem3 = demoArray.pop();
Final Solution: Just Make a Function
The final way is to create a function to handle this all for you. This is very useful if you are frequently creating code that tries to access that last element of an array.
Example:
function last(array) {
return array[array.length - 1];
}
var lastItem4 = last(demoArray);