Get the last item in a JavaScript Array
May 10, 2022 ‐ 2 min read
There are different approaches to accessing the last array item in JavaScript, which to choose depends on whether you wish to remove that element from the array or just access it.
First let's see how you just access the last item of an array, without removing it from that array. You can go for either the slice()
method or use the array length to find the last index.
Using the array length
Using the array length to find the last index of the array is probably the most straight forward way. Since array indexes start counting at 0
you should do the length minus 1
to access the last element.
const days = ["mo", "tu", "we", "th", "fr"];
const last = days[days.length - 1];
console.log(last);
// => 'fr'
When you run this operation on an empty array the result will be undefined
.
const days = [];
const last = days[days.length - 1];
console.log(last);
// => undefined
Using slice()
With slice()
you access the last element when you provide the negative index -1 as a parameter.
const days = ["mo", "tu", "we", "th", "fr"];
const last = days.slice(-1);
console.log(last);
// => ['fr']
As you see the result of this operation is not just the last element, but another array containing just the last element.
To just get the last element, you should use [0]
in combination with slice()
.
const days = ["mo", "tu", "we", "th", "fr"];
const last = days.slice(-1)[0];
console.log(last);
// => 'fr'
Running this operation on an empty array results in undefined
:
[].slice(-1)[0];
// => undefined
By popping off the last element
Another option would be to use the .pop()
method. Instead of just accessing the last element, this method removes the last element from the array and returns it. In some cases this is just what you need.
const days = ["mo", "tu", "we", "th", "fr"];
const last = days.pop();
console.log(last);
// => 'fr'
console.log(days);
// => (4) ['mo', 'tu', 'we', 'th']