JavaScript Get the Last Item in an Array

  1. Use the length Property to Get the Last Item in an Array in JavaScript
  2. Use the pop() Method to Get the Last Item in an Array in JavaScript

The array is used to store multiple values at a time. JavaScript has different methods to get the last item in an array. Every method below will have a code example, which you can run on your machine.

Use the length Property to Get the Last Item in an Array in JavaScript

We can access the last item in the array by using the length property.

Example of the length Property

let arr1=[0, 2, 1, 5, 8];  
const getLastArrItem = (arr) => { 
  let lastItem=arr[arr.length-1];  
  console.log(`Last element is ${lastItem}`); 
}  
getLastArrItem(arr1); 

Use the pop() Method to Get the Last Item in an Array in JavaScript

The array.pop() function is a built-in function in JavaScript. It is used to return and remove the last element of the array. If we do not want to mutate our array, I do not recommend this way.

Example of the pop() Method

let arr1=[0, 2, 1, 5, 8];  
const getLastArrItem = (arr) => {  
  let lastItem = arr.pop();
  console.log(`Last element is ${lastItem}`);
   console.log(`Our array after remove last item: ${arr}`);
}  
getLastArrItem(arr1);

Related Article - JavaScript Array

  • How to Store Key-Value Array in JavaScript
  • How to Empty an Array in JavaScript