Files
30-seconds-of-code/snippets/last.md
Christian Melgarejo Bresanovich ec28d5fa6f Update snippets head and last to type check
Update `head` and `last` to check on empty, undefined, null arrays.
2019-12-11 03:17:18 -03:00

460 B

title, tags
title tags
last array,beginner

Returns the last element in an array.

Check if arr is truthy and has a length property, use arr.length - 1 to compute the index of the last element of the given array and returning 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