Open In App

How to Access the Last Element of an Array in JavaScript ?

Last Updated : 29 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In JavaScript, you can access the last element of an array using the array’s length property. Here are a couple of ways to do it:

Using Array Length

Use the length property to get the last element by subtracting 1 from the array’s length.

Example: Below is an example.

Javascript




let myArray = [1, 2, 3, 4, 5];
let lastElement = myArray[myArray.length - 1];
 
console.log(lastElement); // Outputs 5


Output

5

Using the pop Method

The pop method removes the last element from an array and returns that element. If you just want to access the last element without removing it, you can use this method in combination with a temporary variable.

Example: Below is an example.

Javascript




let myArray = [1, 2, 3, 4, 5];
let lastElement = myArray.pop();
 
console.log(lastElement); // Outputs 5
console.log(myArray); // Outputs [1, 2, 3, 4]


Output

5
[ 1, 2, 3, 4 ]

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads