Search justacoding.blog. [Enter] to search. Click anywhere to close.

October 8th, 2021

5 Ways To Get The Last Element Of An Array In JavaScript

We’ve all been there.

“How do I get the last element of an array in JavaScript?”

It’s a fairly simple JavaScript problem, with a fairly simple solution.

Nowadays, with the advent of ES6 and the like, there are numerous other solutions to this problem outside of the “classic” approach. I thought it’d be a good idea to recap each of these solutions in turn.

Let’s begin!

1. The classic way

I’d say it’s fairly likely that most of us, at one time or another, have pondered the best approach to get the last element of an array in JavaScript.

And the likelihood is that the first solution you stumbled upon looked a little bit like this:

const myArray = [1, 2, 3, 4, 5]
const lastElement = myArray[myArray.length - 1] // 5

This is the classic approach to solving this problem.

We’re using the initial array’s length to lookup the last element of the array by it’s index. We need to subtract 1 from the array’s length because the array is zero-indexed.

As demonstrated, we can simply pass in the relevant index via the square bracket notation and this will give us the last element of the array.

2. The new(er) way, with the at method

There’s a slightly neater, newer approach to this problem now, however:

const lastElement = myArray.at(-1)

The at method receives an integer, positive or negative, and returns whatever element resides at this position (or index) within the array.

Positive integers count from the start of the array, whereas negative integers count from the end of the array.

So as you can see, by supplying -1 to the at method, we’re selecting the very last element in the array.

This way is just a little bit more concise than using the squared bracket approach above.

A note on mutability vs immutability before we continue

Both of the approaches above – using the square bracket notation as well as the at approach, both of these approaches do not modify the initial array.

This is good, as we don’t want to modify the initial array while doing this! We only want to extract some information regarding that array.

By not modifying the initial array, we can say that the array has not been mutated. Or it hasn’t been changed.

change
Immutable entities cannot be changed, mutable ones can

Immutability (and it’s counterpart, mutability) is an important concept in programming in general. I won’t go too far into specifics here, but it’s important to consider whether the operation you are performing in your code mutates your target (the variable, or object, or something else) or not.

Without this consideration, it’s possible to create some quite frustrating bugs or unexpected (and unwanted) behaviours!

3. With pop and slice

If you use pop on your original array, you’ll notice that this returns the last element:

const lastElement = myArray.pop()

Great, that’s what we want – right?

Well, yes and no.

Because pop also modifies (or mutates) the initial array. That’s not what we want. So although we can actually identify the last element of the array with this approach, we’re also mutating the array in the process. So this is not the solution we want!

Introducing slice

The solution to this mutability issue is to use slice.

At first, this may look a little odd:

const lastElement = myArray.slice(-1).pop()

What’s slice doing here?

So slice returns the elements from one array as a new array. The argument passed to the slice function determines at what position we start selecting those items from.

In our case, we’ve passed in -1, which means we want only the last element. If we supplied -2, we’d select the last two elements. If we passed -3 we’d select the last three elements, and so on.

So passing a negative integer means we select x amount of elements from the end of the array, not the start, as would be the case if we passed a positive integer instead (or 0).

As stated, pop returns the last element of the array. It also mutates the array, but we’re only mutating the copy now – not mutating the actual initial array. That’s due to the use of slice. The initial array is unchanged, and we have the element we want – the last element of the array.

An alternative to pop

We can also do something similar without the use of pop:

const lastElement = myArray.slice(-1)[0]

So with this approach, we’re simply selecting the first (or only) element in the array and returning that. It gives the same results as the pop approach above.

Great!

Let’s look at some other approaches.

4. With the spread operator (or the ES6 way)

Here’s a similar solution, but using the spread operator (or syntax):

const lastElement = [...myArray].pop()

This solution is similar to the slice method above because it uses pop — but also doesn’t mutate the initial array. We aren’t modifying the initial array in any way here, even though we’re poping directly.

Again, we’re poping on a copy of the initial array.

That’s what the spread operator (...) is doing. Firstly, we’re copying the initial array through the usage of the spread operator. And then we’re popping like we did above to find the last element!

About JavaScript’s spread operator

If you aren’t familiar with the spread operator, here’s a quick rundown:

It’s a new feature of ES6, and it has multiple different uses, such as:

  • Merging arrays
  • Cloning/coping an array (we’re doing that here!)
  • You can convert a string to an array
  • You can convert a Set to an array

And so on.

The spread operator has numerous other applications outside of these examples.

As stated, in this specific example, we’re using it to clone our initial array before we modify it using pop.

5. Using destructuring (another ES6 way)

Lastly, we can also use ES6’s destructuring to achieve our desired results:

const [ lastElement ] = myArray.slice(-1)

So in this case, we’re destructuring the results of myArray.slice(-1).

The result (or the return value) of this slice is the last element of the array.

To destructure in JavaScript means to break down the iterable entity (so the array or object, in our case specifically — the array) and assign these individual properties to a variable.

Here, we’re assigning the results of our slice operation (the last element of the array) to the variable lastElement. So we’ve destructured the sliced data and bound the relevant piece to a variable! Neat.

As you may have guessed, you could also do something like this:

// destructure the last 2 elements, bind them to variables
const [ lastElement, secondFromLastElement ] = myArray.slice(-2)

// now do the same with the first 2 elements
const [ firstElement, secondElement ] = myArray.slice(0)

Destructuring is really useful as it can lead to clearer, more concise code.

Here’s a similar example, but using an object instead of an array:

const person = { name: "Sarah", age: 45 }
const { name, age, unknownProp } = person
// name => "Sarah"
// age => 45
// unknownProp => undefined (it doesn't exist on the destructured object)

Some would argue it’s simply syntactic sugar, but I’m a huge proponent of anything that makes code more declarative and easier to read!

So, what’s the most efficient way to get the last element of an array in JavaScript?

So we’ve outlined 5 possible approaches that will each provide us with the facility to get the last element of the JavaScript array.

Which solution is most efficient, though? And which should you be using in the reality?

fastest solution
What’s the fastest solution?

There’s a StackOverflow post that analyzes the efficiency regarding the different approaches:

From this, we can clearly conclude that:

  • Solution 1, the “classic” approach is the fastest solution
  • Using pop can be considered fast
  • The other approaches that we have covered, in general, are slower than these two

So there we have it – it’s recommended to use the classic approach (square bracket notation) when finding the last element of the array in JavaScript. That’s if efficiency is your sole and most important concern.

I’d argue that there is a good case for using the at approach if readability and succinctness is most important.

As always – it’s down to the individual developer based on their own priorities and preferences, though.

In summary

That just about wraps up the different approaches we can take to this common problem.

I hope you enjoyed this brief recap and are now more familiar with the various ways you can get the last element of an array in JavaScript! What’s your favourite method?

On the topic of arrays, I’ve got an article that deals with JavaScript exercises specifically revolving around their usage.

If you want to brush up on your JavaScript array skills in general, feel free to check this one out:

It’s part of a mini-series, with 2 other parts currently released:

All of the exercises are short and concise, with the aim being to make it easier to practice various aspects of the JavaScript developer’s toolkit.

Thanks for reading!

Have any questions? Ping me over at @justacodingblog
← Back to blog