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.
Written by: Josh Rowe
Created: May 22, 2022