Code Premix

Get the last item in an array using JavaScript

📅December 3, 2021

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

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

const countries = ["USA", "Canada", "Australia", "India"];

const students = [
  { name: "Glenda Lacey", email: "[email protected]" },
  { name: "Tamzin Brennan", email: "[email protected]" },
  { name: "Chloe Lister", email: "[email protected]" },
  { name: "Shanai Wickens", email: "[email protected]" },
  { name: "Laurence Suarez", email: "[email protected]" }
];

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.

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.

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.

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..!!