As you keep adding more elements to an array, it becomes extremely hard to keep track of the index of each element. There could be a scenario when you don’t care about other elements, but somehow you want to retrieve the last element in the array.
The length property of an array gives us a total number of elements in an array. With the help of this property, we can easily retrieve the last element in the array.
In the following example, we have one global array and upon button click, we simply want to get the last element in the array and display it on the screen. Please have a look over the code example and steps given below.
HTML & CSS
We have 3 elements in the HTML file (div, button, and h1). The div element is just a wrapper for the rest of the elements.
The inner text for the button element is “Get” and for the h1 element, it is “Result”.
We have done some basic styling using CSS and added the link to our style.css stylesheet inside the head element.