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


This is an short tutorial on multiple ways to get last element from an array

Let’s declare an example for an array

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

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

Array.length property returns length of an array.

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

get last element using array index without mutating original array

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

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

This is the simple and fast way of selecting last element from an array.

This will works on all browsers

pop method returns last object with modification of an original array

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

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

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

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

array.slice is an method in ES6 javascript. It returns shallow copy of an an array and creates a new array from start index to 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 reverse method to get last element

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

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

Select last element using Thirdparty libraries

Thirdparty libraries like UnderscoreJs, Lodash and Ramda provides utilities function.

The last function returns last element of an array.

_.last(array);

It is an simple way and need to import those libraries into an application

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.