Get last element of Array in Javascript

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 comment

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