In JavaScript, to get the last element in an array we can do this simply by using the length property.

var lastElement = someArray[someArray.length-1]

In the above code, someArray is our array, and to get the last element in it, we have to get the length of the array. We also have to subtract 1 from the length of the array since array indexing starts at 0. So if our array has 6 items, array[5] would get us the last item in the array.


In the example below, we will have an array of numbers. We will use the length property as we did above to get the last number in the array.

var numbersArray = [4,3,5,8,14,67,56,23];
var lastNum = numbersArray[numbersArray.length-1];

The variable lastNum above would have value 23.

Interactive Example of Getting the Last Element of an Array

Below we will provide code to let the user input as many numbers as they want separated by a comma(,).

Here is the simple HTML set up:

Type as many numbers as you want separated by a comma.

If the numbers are not separated by a comma only, this example will not work.


Get Last Number

We will then create an array of numbers from this input and find the last value using the length property.

To create an array from the string of numbers the user provides, we will use the split() method along with the Array map() method. We will create a getLastNum function to execute this code.

We will update the results below using the textContent property..

function getLastNum(){
  
  //Get the user input
  var userInput = document.getElementById("userArr").value;

  //Convert user input to an array of numbers
  var numbersArray = userInput.split(',').map(Number);

  //Find the last number
  var lastNum = numbersArray[numbersArray.length-1]

  //Display the max number
  document.getElementById("results").textContent = "The last number in the array is: " + lastNum;

}

The final code and output for this example is below:

Code Output:

Type as many numbers as you want separated by a comma.

If the numbers are not separated by a comma only, this example will not work.

Get Last Number

Full Code:

Type as many numbers as you want separated by a comma.

If the numbers are not separated by a comma only, this example will not work.


Get Last Number


<script>

function getLastNum(){
  var userInput = document.getElementById("userArr").value;
  var numbersArray = userInput.split(',').map(Number);
  var lastNum = numbersArray[numbersArray.length-1]
  document.getElementById("results").textContent = "The last number in the array is: " + lastNum;
}

</script>

Hopefully this article has helped you to understand how to use JavaScript to get the last element in an array.

Categorized in:

JavaScript,

Last Update: March 18, 2024