Get the last element of an array using JavaScript
tutorials-kept-simple
Posted on November 4, 2020
In this tutorial, we take a look at understanding different methods of accessing the last element of an array
If you are new to programming or JavaScript, we recommend you read through the entire article. However, If you are just looking for the code, you can skip to the code section below
An array is a container object that holds a fixed number of values of a single type. An array’s length, once created, would remain constant/fixed. Now that we have a basic idea of what an array is, let's find the last element in an array.
Table of Contents
Code
1) Using the array length property
The length property returns the number of elements in an array. Subtracting 1 from the length of an array gives the index of the last element of an array using which the last element can be accessed. The reason we are subtracting 1 from the length is, in JavaScript, the array index numbering starts with 0. i.e. 1st element's index would 0. Therefore the last element's index would be array length-1.
let arry = [2, 4, 6, 8, 10, 12, 14, 16];
let lastElement = arry[arry.length - 1];
console.log(lastElement);
//16
2) Using the slice() method
The slice() method returns specific elements from an array, as a new array object. This method selects the elements starting at the given start index and ends at the given end index excluding the element at the end index. The slice() method does not modify the existing array. Providing one index value returns the element at that position & a negative index value calculates the index from the end of the array.
let arry = [2, 4, 6, 8, 10, 12, 14, 16];
let lastElement = arry.slice(-1);
console.log(lastElement);
//16
3) Using the pop() method
The pop() method pops/removes the last element of an array, and returns it. This method changes the length of the array.
let arry = [2, 4, 6, 8, 10, 12, 14, 16];
let lastElement = arry.pop();
console.log(lastElement);
//16
Performance
Let us now use all three methods on an array to get the last element and check which method is the fastest
let arry = [2, 4, 6, 8, 10, 12, 14, 16];
console.time('array length property');
let lastElement = arry[arry.length - 1];
console.log(lastElement);
console.timeEnd('array length property');
console.time('array slice method');
let lastElement1 = arry.slice(-1);
console.log(lastElement1);
console.timeEnd('array slice method');
console.time('array pop method');
let lastElement2 = arry.pop();
console.log(lastElement2);
console.timeEnd('array pop method');
//Output:
//16
//array length property: 13.798ms
//[ 16 ]
//array slice method: 8.839ms
//16
//array pop method: 0.138ms
As you can see, the pop() method is fastest. You can use it if you are fine with modifying the array. If you don't want to change the array, the slice() method can be used.
Posted on November 4, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.