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
How to get the last element of an array?The steps involved to get the last element of an array are:
- Use array
slice()to return a specific element
- Retrieve the last element using negative index
- Save the last element in a variable
Continue reading to learn more about the various methods.
Table of Contents
- Using the array length property
- Using the slice method
- Using the pop method
- Other Related Concepts
let arry = [2, 4, 6, 8, 10, 12, 14, 16]; let lastElement = arry[arry.length - 1]; console.log(lastElement); //Output: 16
2) Using the slice() methodThe 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); //Output: 16
3) Using the pop() methodThe 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); //Output: 16
PerformanceLet 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.