How to get the last element of an Array in JavaScript

#javascript #array

Last updated on Nov 26, 2020 by Suraj Sharma

In this tutorial, you will learn 3 different ways to get the last element of an array in JavaScript without using the Array.pop() method

1. Using Array.length

JavaScript arrays are zero-indexed, that means the index of the last element is Array.length-1.

const array = ['get', 'the', 'last', 'element'];

const lastElement = array[array.length-1]; // 'element'

2. Using Array.slice() method

We can use the slice() method to get the last element of the array by passing -1 as an argument to the slice() method.

It returns a new array of length 1

const array = [1, 2, 3];

const newArray = array.slice(-1); // [3]

const lastElement = newArray[0]

// or

const [lastElement] = newArray // array destructuring

console.log(lastElement) // 3

Related Solutions

Suraj Sharma is a JavaScript Software Engineer. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.