EN
JavaScript - get last item in array
0 points
In this article, we would like to show you how to get the last item in an array in JavaScript.
Below we present two solutions on how to do that:
- Using square brackets
[]
, - Using
slice()
method.
In this section, we use the array length
property to count the last index in array
. Then we can get the value of the last item.
xxxxxxxxxx
1
var array = ['a', 'b', 'c'];
2
3
var item = array[array.length - 1]; // returns item or undefined
4
5
console.log(item); // c
The below example shows the use of slice()
method with a negative index to get the last item of the array
.
xxxxxxxxxx
1
function getItem(array) {
2
var items = array.slice(-1);
3
return items[0]; // returns item or undefined
4
}
5
6
7
// Usage example:
8
9
var array = ['a', 'b', 'c'];
10
var ltem = getItem(array);
11
12
console.log(ltem); // c