How to Get Last Element of an Array in JavaScript?

Dec 24, 2022

1 min read

Published in

In JavaScript, you can use the array’s length property to access the last element of an array.

Here’s an example:

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

Alternatively, you can also use the pop() method, which deletes and returns the final element of an array:

1
2
3
let arr = [1, 2, 3, 4, 5];
let lastElement = arr.pop();
console.log(lastElement); // Output: 5

Array in Javascript

In JavaScript, an array is a particular object that stores a collection of values. Per value in an array is called an element, and each element has a numerical index that can be used to access it.

You can create an array using the Array constructor or square brackets [].

1
2
let arr1 = new Array();
let arr2 = [];

Users can also initialize an array with data by passing them as arguments to the constructor or using square brackets with a list of elements separated by commas.

1
2
let arr1 = new Array(1, 2, 3, 4);
let arr2 = [1, 2, 3, 4];

You can access an element in an array by its index, which starts at 0.

1
2
3
let arr = [1, 2, 3, 4];
console.log(arr[0]); // Output: 1
console.log(arr[1]); // Output: 2

You can also use the length property to specify the digit of elements in an array.

1
console.log(arr.length); // Output: 4

Know More about JSON :

Sharing is caring!