Retrieve the last element by specifying the index using the array length.
const arr = [1, 2, 3, 4, 5];
// last element by length
console.log(arr[arr.length - 1]);
Use the slice
method to get the last element.
const arr = [1, 2, 3, 4, 5];
// last element by slice
console.log(...arr.slice(-1));
The pop
method removes and returns the last element of an array.
const arr = [1, 2, 3, 4, 5];
// last element by pop
console.log(arr.pop());
Comparing the performance of the three methods.
const arr = [1, 2, 3, 4, 5];
// last element by length
console.time('lastindex');
console.log(arr[arr.length - 1]);
console.timeEnd('lastindex');
// last element by slice
console.time('slice');
console.log(...arr.slice(-1));
console.timeEnd('slice');
// last element by pop
console.time('pop');
console.log(arr.pop());
console.timeEnd('pop');
Result: The pop()
method performs the fastest.
Although using arr.length - 1
is common, the performance difference suggests that using pop()
is the better choice.
ยฉ 2025 juniyunapapa@gmail.com.