Get the last element of an Array in JavaScript

Today we’ll show you how to get the last element of an array in JavaScript. There are multiple ways to get the last item from an array so, in this short article, we will show you a couple of the methods with examples in JavaScript.

Example

Let’s take an example where we will use the two different arrays.

If you want to get the first item then you can use the countries[0] or students[0] but If you want to get the last item without knowing how many items there on the list then you should use the following ways.

Get the last element of an Array

  1. Use an array length
  2. Use slice method
  3. Use slice with pop method

1. Use an array length

Here, we’ll simply use the length to find the last item of an array. Look at the following code.

2. Use slice method

Let’s use the slice() method to get the last element. The slice() method will return a shallow copy of an array. If we pass the -1 as parameter in the method then we will get the last item in an array format. Use the following code to get the last item.

3. Use slice with pop method

Now we will use the slice() method with pop(). The pop() method removes the last element from an array and returns that element. That’s why we need to use the slice() method before use of the pop() method.

That’s it for today.
Thank you for reading. Happy Coding..!!

If you found value in this article,
you can support us by buying me a coffee! ☕

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *