Start of main content
Last array element
JavaScript, Array · Oct 20, 2020

Returns the last element in an array.
- Check if
arr
is truthy and has a length
property.
- Use
Array.prototype.length
to compute the index of the last element of the given array and return it, otherwise return undefined
.
const last = arr => (arr && arr.length ? arr[arr.length - 1] : undefined);
last([1, 2, 3]);
last([]);
last(null);
last(undefined);
More like this

Learn a handful of awesome tips and tricks that you can leverage in your code to make array manipulation a breeze.
Collection · 9 snippets

Array destructuring can be leveraged in many different ways. Here's one of them.
JavaScript, Array · Aug 28, 2022

Learn how to execute a function for each element of an array, starting from the last one.
JavaScript, Array · Oct 10, 2023

Learn how to get the first or last N elements of a JavaScript array, using Array.prototype.slice()
.
JavaScript, Array · Jul 9, 2023