Get last element of Array in Javascript
You can always do it in the fastest way. If performance is a deal breaker for you where you are writing code for million concurrent connections then arr.length -1 is your thing. But if you fancy some ES6 like I do, then read on..
let yourArr = ["a", "b", "c", "d", "e", "f"];
let { length, [length - 1]: lastNode } = yourArr;
console.log(lastNode);
Whoa! What just happened?
The magic of ES6! We just destructured an object and extracted the length then we created another dynamic key and assigned it to lastNode where we caught the last element of array.
And if you dnt wanna screw up your junior devs you can do something like this
let yourArr = ["a", "b", "c", "d", "e", "f"];
let x = Array.from(yourArr).pop()
console.log(x);
Share this article

Destructuring […arr].pop() works but allocates. Length index wins when it matters.
arr.at(-1) is my default now. So much cleaner than length – 1.
Performance note is fair for hot paths. For everything else I reach for slice(-1)[0] out of habit.
Tiny tip but I still see people mutating with pop then push to put it back. Please don’t.