How to get the last element of the array in javascript

Learn how to get the last element from the array in javascript.

There are multiple ways through which we can get the last element from the array in javascript.

Using pop()

We can use the pop() of array which removes and returns the last element of the array.

let arr = [1, 2, 3, 4, 5, 6, 7, 8];
let last = arr.pop();

console.log(last);
//8

console.log(arr);
[1, 2, 3, 4, 5, 6, 7]

If use the pop() method on empty array then it will return undefined.


Using Array length property

Array.length returns the size of the array. we can use this to get the last element from the array.

let arr = [1, 2, 3, 4, 5, 6, 7, 8];
let last = arr[arr.length - 1];

console.log(last);
//8

console.log(arr);
[1, 2, 3, 4, 5, 6, 7, 8]

This method does not modifies the original array.

Using this method on empty array will also return undefined as we are trying to access the index which does not exists.


Using slice()

We can also use the slice() method to get the last element of the array. If we provide negative index -1 to it then it will remove the last item and return it as a new array.

let arr = [1, 2, 3, 4, 5, 6, 7, 8];
let last = arr.slice(-1);
console.log(last);
//[8]

console.log(arr);
[1, 2, 3, 4, 5, 6, 7, 8]

Custom function to get the last elements from the array

We can create our own custom function which will return the n last elements from the array.

let getLast =  (arr = null, n = null) => {
  if (arr == null) return void 0;
  if (n === null) return arr[arr.length - 1];
  return arr.slice(Math.max(arr.length - n, 0));  
};

With this method we can find the n elements from the end. If n is provided then it will return only last element. If Array is not provided then it will return undefined.

let arr = [1, 2, 3, 4, 5, 6, 7, 8];

let last = getLast(arr);
console.log(last);
//8

last = getLast(arr, 2);
console.log(last);
//[7, 8]

last = getLast(arr, 3);
console.log(last);
//[6, 7, 8]

last = getLast(arr, 0);
console.log(last);
//[]

last = getLast();
console.log(last);
//undefined

This function does not manipulates the original array.

Comments

  • Getters allow you to access the return value of a function just as if it were the value of a property. The return value of the function of course is the last value of the array (

Leave a Reply

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