Get last element of array JavaScript

In this tutorial, let’s look at how to get the last element of an array in JavaScript. We’re going to start with the simplest method of extracting the last element by just accessing it using its index.

Then, we’re going to move on to pre-defined methods like slice, splice, at and so on. Finally, let’s look at how to retrieve ‘n’ number of last elements from an array.

Using the length property

The easiest way of getting the last element of an array is just by accessing it using its index.

Every element in an array is at a particular position. These positions start from 0 and are incremented by 1 for each new element in the array.

Finally, the last element has a position/index of array_length – 1, because the first index starts with 0, as you can see in the image below:

Get last element of array JavaScript

Given an array arr, to access the element at the 3rd index, for example, you need to use the syntax arr[3].

So, as you probably guessed by now, to access the last element of an array, where the number of elements is, let’s say, 5, you need to use the syntax arr[4], where 4 is the length of the array (which is 5, in this case) subtracted by 1.

But this is not a very dynamic approach. There’s no guarantee that you’ll always know the length of the array. So, we need a way to dynamically calculate the array’s length and subtract it for our purposes.

That’s where the ‘length’ property comes in. arr.length will calculate the length of the array arr, and return an integer value.

Then, you can use the syntax arr[arr.length – 1] to access and print the last element of the array, as shown in the example below:

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

Accessing an array’s element will not affect the values/elements in the original array. It’s just retrieving a copy of the element.

Use the slice() method to retrieve the last element

You can also use JavaScript’s pre-defined method ‘slice’ to get the same result. There’s a shortcut while using slice though.

As the name implies, ‘slice’ can be used to slice a string and retrieve the substring of our choice. This method produces a copy of the substring, and does not affect the original array in any way.

The slice method takes 2 arguments. The first argument specifies the starting position of the ‘slicing’, and the second (optional) argument specifies the ending position of the slicing.

Then, the browser will slice from starting_pos to ending_pos – 1 (yes, the element at ending_pos will be excluded, but the one at starting_pos will be included).

Also, a great thing with slice is that the ending position is optional. If you just specify the starting position, the browser will slice from that position to the end of the string.

So, to get our desired result, we just need to use arr.slice(arr.length – 1), which will slice only the last element of the string (because there’s nothing else after that).

console.log(arr.slice(arr.length - 1)); //[5] 

As you can see above, you’ve gotten an array (a copy) that has only the last element of the original array inside it. You can retrieve this element to access it.

So far, slice does not seem like a better option than the first one we saw (accessing using index of the element). But that’s not true at all.

Unlike when accessing the last element using the index, with slice, you can use negative indices to specify positions as well.
Look at the image below:

Slice method negative indices

As you can see, the last element has an index of -1, the second last has an index of -2 and so on with the first element having an index of -arr.length.

So, as you can guess, to slice from the last element, and extract nothing else, just specify arr.slice(-1), and you’re good to go!

console.log(arr.slice(-1)); //[5] 

As I specified before, slice creates a copy of the element(s) in another array.

This is to make sure that, if we slice more than one element at a time, they have some place to go. So, to get the lone element we’ve sliced, use the [0] index to retrieve it, as shown below:

console.log(arr.slice(-1)[0]); //5 

Using splice

Just like slice, you can use splice to retrieve the last element as well. Splice is used to replace the elements in an array at the positions we specify, but the simpler version of splice can be used for our purpose as well, as shown in the examples below:

console.log(arr.splice(-1)[0]); //5 
console.log(arr.splice(arr.length - 1)[0]); //5 

There’s a huge problem with splice though.

Since it’s primarily used to replace elements in an array, if you don’t specify what you want the -1’st position replaced with, your browser will just assume that you want it replaced with nothing (that is, you want it removed from the array), so after the process, you’ll be left with one less element, as shown below:

console.log(arr); //[1,2,3,4] 

Use this method carefully.

Use pop to pop the last value of the string

Remember pop()? It’s one of the oldest methods in any programming language, and as the name implies, it can be used to ‘pop’ the last element of an array. So, every time you use pop on an array, it’ll remove the last element, and retrieve it for you.

In the example below, we’ve used arr.pop() to retrieve the last element of our array (5) and print the same. It’ll only retrieve the element, and not place the element in a new array, like with slice.

console.log(arr.pop()); //5 

Just like splice, pop affects the original array as well, so be careful while using it.

console.log(arr); //[1,2,3,4] 

Slice with pop

Remember how we had to access the retrieved element using the 0th index because the slice/splice methods put them in a new array?

If you use the slice method in conjunction with the pop method, you’ll be able to access the element’s value directly, as shown below:

console.log(arr.slice(-1).pop()); //5
console.log(arr); //[1,2,3,4,5] 

Also, since we’re using slice first, pop will not affect the original array in any way.

Slice, spread operator and pop to retain the original array

Another way to make sure pop() does not affect the original array is by using the spread (…) operator.

This operator will create a copy of the original array, and when you use pop() on that, it’ll just be popping the last element of the copy, while keeping the original array intact, as shown below:

console.log([...arr].pop()); //5
console.log(arr); //[1,2,3,4,5] 

Since we’re creating a whole new array (copy), we’re using a lot of resources to arrive at our results. This might affect the performance of your program if your array is huge, so be careful while using this method.

Use the at() method to directly get the last element

Another great way to retrieve the last element is by using the at() method. It’s a very simple method that just extracts one element at the given position.

It also creates only a copy of the extracted value, just like when using indices.

The main advantage of using this method over using the index of the last element directly is that you can use negative indices. So, -1 indicates the last element and you can directly retrieve it without having to find the length of the array, as shown below:

console.log(arr.at(-1)); //5 

Get the last ‘n’ elements of an array

Finally, let’s look at how to modify the methods we’ve seen so far to get the last ‘n’ elements of an array.

Before we start, let’s rule out the methods that won’t work for this problem.

You can’t use the index to retrieve more than 1 element unless you use a loop and create a copy to store the retrieved elements, one at a time. That’s too much of a hassle, but possible.

But even then, you need to access the elements from the nth position from the end, which again makes things needlessly complicated, so let’s keep it on the backburner for now.

In that vein, the at() method won’t work because it retrieves only one element at a time as well.

So, we’re stuck with the remaining 3 methods. The first, and best, being the slice method, where, if you give -n as your starting position, you’ll retrieve from that position till the end of the string, just like we wanted.

console.log(arr.slice(-3)); //[3,4,5] 

You can use the same argument with splice() as well, though it’ll affect your original array, so you’re better off not using this method.

If you’d like to use pop though, you need to use a loop along with it and create a new variable to store the popped values, as shown below:

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

const nRetrieveWithPop = (arr, n) => {
    let arrCopy = [];
    let count = n;
    for(let i = 0; i < n; i++) {
        arrCopy[count-1] = arr.pop();
        count--;
    }
    return arrCopy;
}

console.log(nRetrieveWithPop(arr,3)); //[3,4,5] 

So, what we’ve done in the above lines of code is that, we’ve created a function nRetrieveWithPop that’ll take 2 arguments: the original array arr, and n, which refers to the number of elements you want to retrieve from the end of the array.

Then, inside the function, we’ve created a new empty array arrCopy. This array will hold the retrieved values.

We’ve also copied the value of n to another variable count. I’ll tell you why we’ve done this in a bit.

Then, we’ve created a simple ‘for’ loop that iterates from 0 to n – 1 (n times). For every iteration of the loop, we’re popping the last value of arr using the pop method, and placing it in the arrCopy array, starting from the end.

Why do we start from the end? Well, as per the above example, we want [3,4,5], in that order. But, as you know, pop() pops the last element. So, when iterating, the first element that’ll pop is 5, and not 3.

So, if we place it in the natural order (arrCopy[0] and so on), we’re shooting ourselves in the foot because we end up with [5,4,3].

Also, note how we’ve made the index count – 1 and not count. Well, that’s because array indices go from 0 to count – 1.

So, assign the popped value to arrCopy[count – 1] and then decrement the count value by 1. By using count, we keep the value of ‘n’ intact, hence making sure our ‘for’ loop runs to completion.

Finally, return arrCopy, and that’s it.

That’s it! We’ve looked at the different ways of getting the last element of an array in JavaScript in this tutorial.

Leave a Comment