Files
30-seconds-of-code/javascript/snippets/last.md
2023-05-01 22:35:56 +03:00

551 B

title, type, tags, cover, dateModified
title type tags cover dateModified
Last array element snippet
array
white-laptop 2020-10-20T23:02:01+03:00

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]); // 3
last([]); // undefined
last(null); // undefined
last(undefined); // undefined