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.
1 2 3 4 5 6 7 8 9 | const countries = ["USA", "Canada", "Australia", "India"]; const students = [ ]; |
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
Here, we’ll simply use the length to find the last item of an array. Look at the following code.
1 2 3 4 5 | countries[countries.length - 1]; // Output: "India" students[students.length - 1]; // Output: { name: "Laurence Suarez", email: "[email protected]" } |
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.
1 2 3 4 5 | countries.slice(-1)[0]; // Output: "India" students.slice(-1)[0]; // Output: { name: "Laurence Suarez", email: "[email protected]" } |
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.
1 2 3 4 5 | countries.slice(-1).pop(); // Output: "India" students.slice(-1).pop(); // Output: { name: "Laurence Suarez", email: "[email protected]" } |
That’s it for today.
Thank you for reading. Happy Coding..!!