You can get the last element of a JavaScript array in the following ways:
Directly Accessing the Last Element
You can simply access the last element of an array directly (i.e. using the squared bracket notation) by specifying its index (which is going to be array.length - 1
in this case). For example:
const arr = [ 1, 2, 3, 4 ]; const lastElem = arr[arr.length - 1]; console.log(lastElem); // 4 console.log(arr); // [1, 2, 3, 4]
When you try to access the last element on an empty array, undefined
is returned:
const arr = []; const lastElem = arr[arr.length - 1]; console.log(lastElem); // undefined
Using Array.prototype.at()
Starting with ES13, you can use the Array.prototype.at()
method in the following way to access the last element:
// ES13+ const arr = [ 1, 2, 3, 4 ]; const lastElem = arr.at(-1); console.log(lastElem); // 4 console.log(arr); // [1, 2, 3, 4]
When you try to access the last element on an empty array, undefined
is returned:
// ES13+ const arr = []; const lastElem = arr.at(-1); console.log(lastElem); // undefined
This post was published (and was last revised ) by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.