Ways to get last element of array JavaScript

Last Updated On Wednesday 13th Apr 2022

JavaScript get last element of array

Without affecting original array

	var arr = [1,2,3,4,5];

console.log(arr.slice(-1)[0])
console.log(arr[arr.length-1])
const last = [...arr].reverse();
console.log(last)

let copyArr = [...arr];
console.log(copyArr.reverse()[0]);
	
	5
5
[ 5, 4, 3, 2, 1 ]
5
	

last element back on after a pop()

  • arr.pop() is exactly as efficient as arr[arr.length-1].

Modifies original array

	var arr = [1,2,3,4,5];

console.log(arr.pop())
arr.push(5)
console.log(...arr.splice(-1));
	
	5
5
	
	const myArray = [1, 2, 3]

console.log(myArray.at(-1));

// 3
	
  • The at() method takes an integer value and returns the item at that index, allowing for positive and negative integers.
	var arr = [1, 2, 3];
var last_element = arr.slice().reverse()[0];

console.log(last_element) // 3
	

References