How To Get The Last Element Of An Array In Javascript

Get the last element of an array in Javascript

Working with an array always is a crucial thing in Javascript. So how to get the last element of an Array in Javascript? Let’s go into detail.

Get The Last Element Of An Array In Javascript

Solution 1: Use length – 1

The length method will return the length of your array, so if you minus it by one, it will be the index of your array’s last element.

Example :

const anArray = [
  "Apple",
  "SamSung",
  "Xiaomi",
  "Huawei",
  "Lenovo",
  "Sony",
  "Asus",
  "Viettel",
];

const lastEle = anArray[anArray.length - 1];
console.log(lastEle);

Output :

Viettel

Solution 2: Use slice() method

Slice method will extract your array from the start index to the end and return it without changing your origin array.

Syntax:

array.slice(start,end)

But slice() also has a beneficial mechanism that helps you get your array’s last element. It is you can pass in a negative number. And with the negative number, the index will count reverse from the end of your array. So with “-1”, you can get the last element of your array.

Example:

const anArray = [
  "Apple",
  "SamSung",
  "Xiaomi",
  "Huawei",
  "Lenovo",
  "Sony",
  "Asus",
  "Viettel",
];

const lastEle = anArray.slice(-1);
console.log(lastEle);

Output :

[ 'Viettel' ]

Solution 3: Use pop() method

The pop () method will remove the last element of your array and return it. So you can catch it by assign to a variable. But the side effect is the pop() method will change your origin array, which is a terrible practice for the developer.

Syntax :

array.pop()

Example :

const anArray = [
  "Apple",
  "SamSung",
  "Xiaomi",
  "Huawei",
  "Lenovo",
  "Sony",
  "Asus",
  "Viettel",
];

const lastEle = anArray.pop();
console.log(lastEle);
console.log(anArray);

Output :

Viettel

Solution 4: Create your own function

You can also create your function with the name getLastElement, which will help you get your array’s last element.

Example :

const anArray = [
  "Apple",
  "SamSung",
  "Xiaomi",
  "Huawei",
  "Lenovo",
  "Sony",
  "Asus",
  "Viettel",
];

const getLastElement = (array) => {
  return array[array.length - 1];
};

console.log(getLastElement(anArray));

Output:

Viettel

It will be a lot of ways for you to get the last element of your array by combining some methods in Javascript. I believe that you will find out about all of them.

Summary

In this tutorial, I showed and explained some ways to get the last element of an array in Javascript by length, slice, pop method, or create your function to help you do it.

Maybe you are interested:

Leave a Reply

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