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
- Other Related Concepts
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.
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.
PerformanceLet us now use all three methods on an array to get the last element and check which method is the fastest
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.