Javascript Get Last Element of Array

Javascript Get Last Element of Array

In this tutorial, I will explain javascript get last element of array. Before getting started, you must know what is an array and the length property of the array.

Also read, Generate Javascript Random Number between 1 and 10

What is an array:-

  • As we all know that an array is a variable that can hold more than one value or multiple values at a time and the index of an array starts with 0.
  • An array is declared with the keyword const.

Example of an array:-

const companies = ['TCS','IBM','HCL','INFOSYS'];

Length Property of the array:-

The length property counts the number of values in an array.

For eg:- If we want to find the length of the above array then it can be obtained as shown below

let company length = companies.length;

To store the length of the above array, you can declare another variable with the let keyword that holds the result which means the number of values of the above array.

In order to find javascript get last element of array, you can use the below syntax and store it in a variable as shown below

let variable name = array name[array name.length - 1];

Now, get the last of the element of the companies array as shown below

let lastelementofcompany = companies[companies.length - 1];

So, the result will be “INFOSYS“. To view the result in your browser, you can use an HTML div element with an id attribute or class attribute and then get the result with the help of a document.getElementById(“id attribute”).value or by using a javascript function.

Conclusion:- I hope this tutorial will help you to understand the concept. If there is any doubt then please leave a comment below.

Leave a Comment