How to Get the Last Element of a JavaScript Array?

Learn about the best way of getting the last element of an array in JavaScript

You can get the last element of a JavaScript array in the following ways:

Get the Last Element Without Modifying the Original Array

You can simply, directly access the last element of an array by specifying its index (which is going to be array.length - 1 in this case). Using this approach does not modify the original array. For example:

const arr = [ 1, 2, 3, 4 ];
const lastElem = arr[arr.length - 1];

console.log(lastElem); // output: 4
console.log(arr); // output: [1, 2, 3, 4]

When you try to access the last element on an empty array, you will get undefined:

const arr = [];
const lastElem = arr[arr.length - 1];

console.log(lastElem); // output: undefined

Please note that there are a couple of other ways in JavaScript to get the last element of an array in an immutable way, however, this is the fastest, and perhaps the best way.

Get the Last Element and Remove it From the Original Array

If you wish to access the last element, as well as remove it from the original array, then you can simply use the Array.prototype.pop() method, for example, like so:

const arr = [ 1, 2, 3, 4 ];
const lastElem = arr.pop();

console.log(lastElem); // output: 4
console.log(arr); // output: [1, 2, 3]

Using the Array.prototype.pop() method on an empty array would return undefined. For example:

const arr = [];
const lastElem = arr.pop();

console.log(lastElem); // output: undefined

Hope you found this post useful. It was published . Please show your love and support by sharing this post.