This article discusses the preferred way to retrieve the last element of an Array in JavaScript.
Tip 7 in this Useful JavaScript Hacks Article proposes the following method to get the last item in an array.
var array = [1,2,3,4,5,6]; |
It is a very neat and readable alternative to the often seen:
var array = [1,2,3,4,5,6]; |
Performance
I created the following quick performance test in Node (v5.6.0) to see how this syntax (syntax1.js
) compares to the more traditional one (syntax2.js
):
console.time('array slice'); |
Here are the results:
$ node index.js |
Slicing the array is 20 times more taxing than accessing the last item directly.
Simplicity
The syntax1 is a lot simpler to write and read and I will certainly start using it when performance is not a concern:
Empty array
It works well when the array is empty:
var array = []; |
Get the last few elements in the array
You can use the same technique to slice the array starting from the end of it. Pretty cool.
var array = [1,2,3,4,5,6]; |