OneBite.Dev - Coding blog in a bite size

get last element of array in javascript

Code snippet for how to how to get last element of array in javascript with sample and detail explanation

In the world of Javascript, dealing with arrays is going to be a frequent task. One of the common operations on arrays you may need to perform is accessing the last element. This short article will guide you on how to get the last element of an array in Javascript.

Code Snippet: Accessing the Last Element of an Array

var arr = [1, 2, 3, 4, 5];
var lastElement = arr[arr.length - 1];
console.log(lastElement);

Code Explanation for Accessing the Last Element of an Array

Let’s break down this code.

We start by declaring an array arr with five elements for demonstration. The array could be any size.

var arr = [1, 2, 3, 4, 5];

The main trick to get the last element is by using the length property of the array combined with the array index.

Since the index in arrays begins from 0, not 1, the last element of an array is at index length - 1, not length. Thus, we access the last element of the array by arr[arr.length - 1].

var lastElement = arr[arr.length - 1];

Finally, we print the value of the last element of the array using console.log().

console.log(lastElement);

When you run the above code, the output will be ‘5’, as it is the last element in the array.

Remember, this code will only work if the array is not empty, so it’s always a good idea to check the length of the array before trying to access the last element. If the array is empty, arr[arr.length - 1] will return undefined.

javascript