EN
JavaScript - get second last item in array
0
points
In this article, we would like to show you how to get the second last item in an array working with JavaScript.
Below we present two solutions on how to do that:
- Using square brackets
[], - Using
slice()method.
1. Practical example using square brackets
In this section, we use the array length property to count the second last index in array. Then we can get the value of the last item.
// ONLINE-RUNNER:browser;
var array = ['a', 'b', 'c', 'd'];
var result = array[array.length - 2];
console.log(result); // 'c'
2. Using slice() method
The below example shows the use of slice() method with a negative indexing to get the second last item of the array.
// ONLINE-RUNNER:browser;
function getItem(array) {
var items = array.slice(-2);
return items[0]; // returns item or undefined
}
// Usage example:
var array = ['a', 'b', 'c', 'd'];
var item = getItem(array);
console.log(item ); // 'c'