First element and last element in a JavaScript array?

Front End TechnologyJavascriptObject Oriented Programming

An array is a group of elements. Each element has its own index value. We can access any element using these indexes. But in the case of the last element, we don't know the index until we know the number of elements present in the array. In this case, we have to use logic. Let's discuss these details in a nutshell.

Accessing the first element

Since we know the index of the first element we can get the value of that element very easily. Let the array be arr. then the value of the first element is arr[0].

Example

In the following example, there are arrays called array1 and array2 and both the arrays consist of '4' elements. Since the index of the first element is '0', the value of the first element is array1[0] and array2[0].

<html>
<body>
<script>
   var array1 = ["Tutorix","Tutorialspoint","Javascript","Java"];
   document.write(array1[0]);
   document.write("</br>");
   var array2 = ["Elon musk","Bilgates","Larry page","slim helu"];
   document.write(array2[0]);
</script>
</body>
</html>

Output

Tutorix
Elon musk

Accessing the last element

If we know the number of elements in the array, using index we can find the last element. For instance, if an array named arr consists of 5 elements then the last element is arr[4]. But in case if we are not aware of a number of elements then we have to proceed logically. The Last element is nothing but the element at the index position that is the length of the array minus-1. If the length is 4 then the last element is arr[3].

Example

In the following example, the last element of arrays named array1 and array2 have been found out and the results were displayed in the output. In accessing the last element of the former array, a normal index is used whereas for the latter array, the length of the array is used.

<html>
<body>
<script>
   var array1 = ["Javascript","Java","Spring","springboot"];
   document.write(array1[3]);
   document.write("</br>");
   var array2 = ["Elon musk", "Bilgates", "Larry page", "slim helu", "jackma", "Ambani"];
   document.write(array2[array2.length-1]);
</script>
</body>
</html>

Output

springboot
Ambani
raja
Published on 20-Aug-2019 08:19:15
Advertisements