How to Get Last Element in Array in Javascript

In this tutorial, you will learn how to get last element in array in javascript. We use the push() method whenever we want to add an element to an array. This method always appends an element at the end of the array.

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.
  • We have also included our javascript file script.js with a script tag at the bottom.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="style.css">
    <title>Document</title>
</head>
<body>
    
    <div class="container">
        <button>Get</button>
        <h1>Result</h1>
    </div>

    <script src="script.js"></script>
</body>
</html>
.container {
    display: flex;
    flex-direction: column;
    align-items: center;
}

button {
    padding: 10px 20px;
}

Javascript

  • We have selected the button element and h1 element using the document.querySelector() method and stored them in btnGet and result variables respectively.
  • We have a global variable fruits and it holds an array of strings.
  • We have attached the click event listener to the button element.
  • In the event handler function, we are using the length property of the fruits array and subtracting 1 from it to get the index of the last element.
  • We are displaying that last element on the screen using the innerText property of the h1 element.
let btnGet = document.querySelector('button');
let result = document.querySelector('h1');

let fruits = ['Apple', 'Orange', 'Mango', 'Kiwi', 'Grapes', 'Banana', 'Dragon Fruit'];

btnGet.addEventListener('click', () => {
    result.innerText = fruits[fruits.length-1];
});
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •