Skip to Content

How to Get the Last Array Element with JavaScript

In this quick tutorial, you'll learn a few different methods for retrieving the last element of an array in JavaScript.

The Array.at() Method

ECMAScript 2022 is a new JavaScript standard to be released in June 2022, introducing the Array.at() method which allows us to get the last element of an array by passing a value of -1 to the method:

var my_array = [1, 2, 3, 4];
var last = my_array.at(-1);

console.log(last);
// 4

The Array.length Method

The original method for retrieving the last array element's value is by passing in a dynamic Array.length:

var my_array = [1, 2, 3, 4];
var last = my_array[my_array.length - 1];

console.log(last);
// 4

Conclusion

Both JavaScript methods are effective in retrieving the last array element. There are absolutely no differences in speed when running speed tests between the two different methods, so knock yourself out and use whichever works for you.

Created: May 22, 2022

Comments

There are no comments yet. Start the conversation!

Add A Comment

Comment Etiquette: Wrap code in a <code> and </code>. Please keep comments on-topic, do not post spam, keep the conversation constructive, and be nice to each other.