Top 5 Ways to get Last Element from an Array in JavaScript

In this brief tutorial, we’ll explore various methods to get the last element from an array.

Let’s declare an example for an array.

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

Arrays in programming languages typically start with an index of 0, where array[0] represents the first element, and array[array.length-1] represents the last element.

The Array.length property provides the length of an array.

Above code, the last element from an array is 9.

For additional reference, you can refer to other posts on Javascript Add,Delete from Array

Now, let’s explore multiple ways to retrieve the last element of an array in JavaScript:

Using Array Index without Mutating the Original Array

The last element can be obtained using array indexing without modifying the original array.

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

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

This method is simple, fast, and universally compatible with all browsers.

Using the pop Method without Modify an original array

The pop() method in an array returns the last element but alters the original array by removing the last element.

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

To obtain the last element without modifying the original array, we’ll explore alternative methods.

Using ES6 Array slice Method

The array.slice method in ES6 JavaScript returns a shallow copy of an array, creating 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 process can be simplified:

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

Using the reverse Method

An alternative approach involves reversing the original array using the reverse() method and then retrieving the first element using index 0.

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

Using Third-party libraries

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

The last function, for instance, returns the last element of an array.

_.last(array);

While this method is straightforward, it requires importing these libraries into your application.

Conclusion

In conclusion, we’ve explored multiple ways to retrieve the last element and index from an array, including array indexing, the pop method, ES6 array slice, array reversal, and leveraging third-party libraries such as UnderscoreJS and Lodash. Each method comes with its own advantages and use cases.