Last Updated : Jan 1, 2023
You can skip ahead to the code part below if you're only interested in the code.
A container object that stores a number of values of a single type is called an array.
The length of an array would remain constant/fixed once it was created. Let's identify the last element in an array now that we have a fundamental understanding of what an array is.
1. Array length property
<html> <head> <title></title> </head> <body> <script> let arry = [2, 10, 12, 14, 16]; let lastElement = arry[arry.length - 1]; console.log(lastElement); </script> </body> </html>
- Number of elements in an array is returned via the length attribute. You can Subtract 1 from the length of an array which returns the index of the array's last element, which can be used to access the last element.
2. Using the slice() method
<html> <head> <title></title> </head> <body> <script> let arry = [2, 10, 12, 14, 16]; let lastElement = arry.slice(-1); console.log(lastElement); </script> </body> </html>
- This method returns a new array object containing particular elements from an array. This method picks elements beginning at the specified start index and ending at the specified end index, except the element at the specified end index.
- The array is not modified by the slice() method. A positive index value calculates the index from the beginning of the array, while a negative index value counts the index from the end of the array.
3. Using pop() method
<html> <head> <title></title> </head> <body> <script> var myList = ["Peter", "Smith", 25, 23, "Random String", 10] var lastElement = myList.pop(); console.log(lastElement) console.log(myList) </script> </body> </html>
- The pop() method returns the last element while also removing it. However, we may prevent this functionality by temporarily copying the list in memory and calling pop() on the copy, keeping the original list intact, if we utilise the spread operator from ES6.
- If you do not need the original list to stay intact, you can pop elements from it; however, if you do, you can make a copy and pop() from that.
The fastest technique is pop(). If you don't mind changing the array, you can use it. The slice() method can be used if you don't want to modify the array.