Clue Mediator

Get the last element of an Array in JavaScript

📅October 28, 2020

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.

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

const students = [
  { name: "Glenda Lacey", email: "glenda.lacey@mailinator.com" },
  { name: "Tamzin Brennan", email: "tamzin.brennan@mailinator.com" },
  { name: "Chloe Lister", email: "chloe.lister@mailinator.com" },
  { name: "Shanai Wickens", email: "shanai.wickens@mailinator.com" },
  { name: "Laurence Suarez", email: "laurence.suarez@mailinator.com" }
];

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: "laurence.suarez@mailinator.com" }

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: "laurence.suarez@mailinator.com" }

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: "laurence.suarez@mailinator.com" }

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