In this article, some light will be shed on how you can retrieve the initial and final item of an array.
How are items retrieved in an array?
To learn about this concept, it is important to first learn how the index is used to retrieve any item from the array that is desired. The syntax provided down below is an illustration it can be achieved:
In the code above, the 7th element(since the index starts from 0) of the “sampleArray” is being retrieved and stored into a variable named “element”.
The first item
Applying what we learned in the section above we can get the first item of an array with ease. Follow the example below:
Here we simply apply what we learned above. The array always starts with the 0th index, which means that its first element is always on the index 0. The algorithm is being implemented in the following snippet:
The last item
The retrieval of the last element requires a couple more steps compared to the first. This is because the developer is not always aware of what the maximum size of the array will be. Due to this a standard method will be applied that works for any size of the array. Below you are given an illustration for this:
const last = sampleArray[size];
In this code an additional function is being used. The “sampleArray.length” function is being utilized where “sampleArray” is the name of your array. This operation is used to compute the full number of elements inside an array, then stores it into a variable. Once we have the length, we subtract it by one and use it as the index of the final item. The sample snippet is shown below:
The first item of an array can be retrieved using the 0th index of the array whereas the final item requires the use of the “sampleArray.length” function(which returns the total length of an arrow). Through this article, we have seen how the first and last item from an array of any size can be retrieved.