javascript get second last element in array

How to Get the Second Last Element in an Array using JavaScript

Arrays are an essential data structure in JavaScript, and they allow us to store a collection of values in a single variable. Sometimes, we may need to access specific elements in an array, such as the second last element. Here's how we can do it.

Method 1: Using the length property

One way to get the second last element in an array is by using the length property along with the index position of the element we want to retrieve. Here's how it works:


const myArray = ['apple', 'banana', 'cherry', 'date', 'elderberry'];
const secondLast = myArray[myArray.length - 2];

console.log(secondLast); // Output: 'date'

In this example, we have an array called myArray that contains five elements. We want to retrieve the second last element, which is 'date', so we subtract two from the length of the array and use that as the index position to access the element.

Method 2: Using the slice method

Another way to get the second last element in an array is by using the slice method to create a new array with only the last two elements, and then retrieving the first element of that new array. Here's how it works:


const myArray = ['apple', 'banana', 'cherry', 'date', 'elderberry'];
const lastTwo = myArray.slice(-2);
const secondLast = lastTwo[0];

console.log(secondLast); // Output: 'date'

In this example, we use the slice method with a negative argument to create a new array called lastTwo that contains the last two elements of myArray. Then, we retrieve the first element of lastTwo, which is the second last element of myArray.

Conclusion

There are multiple ways to get the second last element in an array using JavaScript, and which method you choose may depend on the specific use case. However, both of the methods we covered here should work in most situations.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe