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.

syntax1.js
1
2
var array = [1,2,3,4,5,6];
console.log(array.slice(-1)[0]); // 6

It is a very neat and readable alternative to the often seen:

syntax2.js
1
2
var array = [1,2,3,4,5,6];
var val = array[array.length - 1]; // 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):

index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
console.time('array slice');
for(var i = 0; i < 1000000; i = i + 1) {
var array = [1,2,3,4,5,6];
var val = array.slice(-1)[0];
}
console.timeEnd('array slice');
console.time('array index');
for(var i = 0; i < 1000000; i = i + 1) {
var array = [1,2,3,4,5,6];
var val = array[array.length - 1];
}
console.timeEnd('array index');

Here are the results:

1
2
3
$ node index.js
> array slice: 92.430ms
> array index: 4.820ms

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:

1
2
3
var array = [];
console.log(array.slice(-1)); // return []
console.log(array.slice(-1)[0]); // returns undefined

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.

1
2
3
4
var array = [1,2,3,4,5,6];
console.log(array.slice(-1)); // [6]
console.log(array.slice(-2)); // [5,6]
console.log(array.slice(-3)); // [4,5,6]