Top 5 ways to get the last element from an array in javascript

It is a short tutorial on multiple ways to get the last element from an array.

Let’s declare an example for an array. You can also check other posts on Javascript Add,Delete from Array

let array = [12, 1, 8, 9];

Arrays in any programming language always start with index=0, which means array[0] returns the first element, array[array.length-1] returns the last element of an array.

Array.length property returns the length of an array.

Following are Multiple ways we can retrieve the last element of an array in JavaScript Above code, the last element from an array is 9.

Get the last element using array index without mutating the original array

As array.length returns the number of elements in it. The array always starts with zero indexes and the last element index is an array.length-1

console.log(array[array.length - 1]);

It is a simple and fast way of selecting the last element from an array. It works on all browsers.

pop method returns the last object with modification of an original array

array pop() method returns the last element from an array, But it modifies the original array by removing the last element

console.log(array.length); // 4
console.log(array.pop()); // 9
console.log(array.length); // 3

How do you select the last element without mutating the original array?

Ecmascript (ES6) array slice method to get the last element of an array

array.slice is a method in ES6 javascript. It returns a shallow copy of an array and creates a new array from a start index to an end index.

console.log(array.length); //4
console.log(array.slice(-1)); // (1) [9]
console.log(array.slice(-1)[0]); // 9
console.log(array.length); //3

with destructing assignment operators, The same can be simplified as follows

[lastElement] = array.slice(-1);
console.log(lastElement); //9

Using a reverse method to get the last element

It is also a simple approach by reversing an original array using the reverse() method. Next, get the first element using index=0.

var reverseArray = array.reverse();
console.log(reverseArray[0]); // 9

Select the last element using Third-party libraries

Third-party libraries like UnderscoreJs, Lodash, and Ramda provide utility functions.

The last function returns the last element of an array.

_.last(array);

It is a simple way and needs to import those libraries into an application.

Conclusion

Multiple ways to retrieve the last element and index from an array.

  • Array index
  • Array Pop method
  • Ecmascript Array slice method
  • reverse an array and first index element
  • UnderscoreJS and Lodash last property