10 minutes read

How to Get Second Last Element of Array in Javascript

Summary:In these code snippets, we are going to learn different ways to get the second last element of an array in javascript.

Suppose an array of fruits.

const fruits = ['apple', 'banana', 'pineapple', 'mango', 'cactus']

We already know that we can access the array elements by their index. And we can use the same to access the last elements of an array in Javascript.

Here are some simple ways to get the second array element in Javascript.

Using The Length Property

fruits[fruits.length-2] //mango

Using The Reverse Method

fruits.reverse()[1] //mango

Using the Slice method

fruits.slice(-2, -1)[0]) //mango

Explanation:

The negative index in Javascript means to select the elements from the last of the array.

The slice method will create a new array of the second last element array in javascript and the zero index will select that.

Join Our Youtube Channel

Subscribe