Get The Second Last Element Of An Array In JavaScript

To get the second last element of an array in JavaScript, you can use any of these methods –

  1. Use the arr.length-2 index to access the second last element of an array.
  2. Use the arr.at(-2) index to access the second last element of an array.
  3. Use the arr.slice(-2, -1)[0] to access the second last element of an array.

Let’s discuss each of these methods in detail below.

get the second last element of an array in javascript

arr[arr.length-2] To Get The Second Last Element Of An Array In JavaScript

This is the most common and straightforward method to get the second last element of an array in JavaScript. The arr.length-2 index gives us the second last element’s position in the array.

We can use this index with the square brackets[] notation.

Here is an example –

function getSecondLast(arr) {

   return arr.length>=2 ? arr[arr.length-2] : null;

}

console.log(getSecondLast([1, 2, 3, 4]));

Output: 3

Use The arr.at() Method To Get The Second Last Element Of An Array

If you are using the ES6 version of JavaScript, then you can use the arr.at() method to get the second last element from an array.

The at() method was introduced in the ES6 version and it is used to access a specific element of an array –

const arr = ['a', 'b', 'c', 'd'];

console.log(arr.at(2));

Output: c

Use The arr.slice(-2, -1)[0] To Get The Second Last Element Of An Array

This is a slightly more complicated method to get the second last element of an array in JavaScript. Here we are using the arr.slice() method with the -2 and -1 indexes.

The slice() method is used to extract a part of an array. The first parameter is the start index and the second parameter is the end index (not including).

In our case, we want to get all elements starting from the second last element till the last element. Hence we use the -2 and -1 indexes.

However, this gives us an array with only one element (the second last element). Hence, to get that single element, we use the arr.slice(-2, -1)[0] notation.

Here is an example to illustrate this method –

function getSecondLast(arr) {

   return arr.length>=2 ? arr.slice(-2, -1)[0] : null;

}

console.log(getSecondLast([1, 2, 3, 4]));

Output: 3

Conclusion

In this tutorial, we saw three different methods to get the second last element of an array in JavaScript. We also discussed each of these methods in detail with examples.

I hope this tutorial was clear and helpful. If you have any doubts or questions, please post them in the comments section below.

Happy learning! 🙂

Leave a Reply