This blog will explain the methods to fetch an array’s last element using JavaScript.
How to Get/Fetch Last Element in Array in JavaScript?
To fetch the array’s last element in JavaScript, the following methods can be applied:
The above approaches will now be discussed one by one!
Method 1: Get Last Element in Array in JavaScript Using length Property
The “length” property specifies the length of an array or a string. This property can be utilized to get the array’s last element by specifying the length of an array and subtracting “1” from it to access the last array element.
Syntax
In the above syntax, “length” represents the length of the specified string.
The following example will clarify the stated concept.
Example
In this example, an array named “array” will be defined with the specified elements:
Now, subtracting “1” from the total array length will fetch the last array element and store in a variable named “lastElement”:
Lastly, the updated array will be displayed on the console using the “console.log()” method:
The given output signifies that we have successfully fetched the last element of the array, which is “1”:
Method 2: Get Last Element in Array in JavaScript Using Index Positioning Technique
“Index Positioning” technique is applied in the case of accessing some particular array value or performing operations between two array elements. This technique can also be utilized to access the last array element by positioning its specified index in an array.
Syntax
Here, “index” refers to the array index starting from “0” as the first position up to so on.
Example
Firstly, an array of the string and integer values will be defined:
Next, the index of the last array element will be accessed and stored in a variable named “lastElement”:
Lastly, the resultant array will be logged on the console:
Output
We have compiled the easiest methods for getting the array’s last element in JavaScript.
Conclusion
To get the last element in an array in JavaScript, apply the “length” property, which will refer to the array’s length, and subtract “1” from it to access the last array element or apply the “index positioning” technique to fetch the particular index of the last array element and display it on the console. This write-up demonstrated the methods to get the array’s last element in JavaScript.