Get the last Element of an Array in JavaScript

avatar

Borislav Hadzhiev

Tue Oct 05 20212 min read

Get the last Element of an Array #

To get the last element of an array, access the array at index [array.length - 1]. The calculation evaluates to the index of the last element in the array.

index.js
const arr = ['a', 'b', 'c']; const lastElement = arr[arr.length - 1]; console.log(lastElement); // ๐Ÿ‘‰๏ธ c
Indexes are zero-based in JavaScript, that's why we have to subtract 1 from the array's length to get the index of the last element in the array.

Other ways to get the last element of an array, include Array.pop and Array.slice.

You can get the last element of an array, by calling the pop method on the array. The pop method mutates the original array and returns its last element.

index.js
const arr = ['a', 'b', 'c']; // ๐Ÿ‘‡๏ธ mutates the original array const lastElement = arr.pop(); console.log(lastElement); // ๐Ÿ‘‰๏ธ c console.log(arr) // ๐Ÿ‘‰๏ธ ['a', 'b']

The Array.pop method returns the last element of the array, but it also mutates the original array.

Calling the pop method on the array removes the last element, leaving the array with just 2 elements. This can be confusing if you have to perform other operations on the array.

In general, operations that cause mutation are considered a bad practice, because they're difficult to track and reason about.

To get the last element of an array:

  1. Pass -1 as an argument to the Array.slice method
  2. The method returns a new array containing the last element from the original array
  3. Assign the element from the new array to a variable
index.js
const arr = ['a', 'b', 'c']; const lastElement = arr.slice(-1)[0]; console.log(lastElement); // ๐Ÿ‘‰๏ธ c

Passing -1 to the Array.slice method means, that we want a new array containing only the last element of the original array.

We then assign the only element in the new array to a variable.

The Array.slice method does not mutate the original array, instead it returns a new array.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee