Categories
ES6

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);

Leave a Reply