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

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 ]

Using array slice method

In this approach we use array slice method. Here we pass a negative index to slice, like -1, it starts the extraction from the end of the array and we access last element from 0’th index.

Syntax:

lastelement= array.slice(-1)[0]

Example: In this example the slice method to access the last element of the array. The slice(-1) returns an array containing the last element, and [0] accesses that element.

JavaScript
let array = [1, 2, 3, 4, 5, 6];
let lastElement = array.slice(-1)[0];
console.log(lastElement);

Output
6



Reffered: https://www.geeksforgeeks.org


JavaScript

Related
How to Create Different Types of Arrays in JavaScript ? How to Create Different Types of Arrays in JavaScript ?
How to Concatenate Two Variables in JavaScript ? How to Concatenate Two Variables in JavaScript ?
What is the use of the Math.random Function in JavaScript ? What is the use of the Math.random Function in JavaScript ?
How to Check if a Variable is of Type Number in JavaScript ? How to Check if a Variable is of Type Number in JavaScript ?
How to Create a Single Line Comment in JavaScript ? How to Create a Single Line Comment in JavaScript ?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
13