How to Access the Last Element of an Array in JavaScript ?
Last Updated :
29 Jan, 2024
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);
|
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);
console.log(myArray);
|
Share your thoughts in the comments
Please Login to comment...