Skip to content
the poor coder

javascript get second last element in array

Poor Man
Published
Reading time
1 min read
On this page

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:

Text

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:

Text

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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC