JavaScript, Array

Returns the last element in an array.

  • Check if arr is truthy and has a length property.
  • Use Array.prototype.length - 1 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]); // 3
last([]); // undefined
last(null); // undefined
last(undefined); // undefined

Recommended snippets & collections

  • JavaScript Array Tricks

    Snippet collection

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

  • forEachRight

    JavaScript, Array

    Executes a provided function once for each array element, starting from the array's last element.

  • initial

    JavaScript, Array

    Returns all the elements of an array except the last one.

  • unzipWith

    JavaScript, Array

    Creates an array of elements, ungrouping the elements in an array produced by zip and applying the provided function.