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:

Directly Accessing the Last Element

You can simply access the last element of an array directly (i.e. using the squared bracket notation) by specifying its index (which is going to be array.length - 1 in this case). For example:

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

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

When you try to access the last element on an empty array, undefined is returned:

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

console.log(lastElem); // undefined

Using Array.prototype.at()

Starting with ES13, you can use the Array.prototype.at() method in the following way to access the last element:

// ES13+
const arr = [ 1, 2, 3, 4 ];
const lastElem = arr.at(-1);

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

When you try to access the last element on an empty array, undefined is returned:

// ES13+
const arr = [];
const lastElem = arr.at(-1);

console.log(lastElem); // undefined

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