Files
30-seconds-of-code/snippets/last.md
Angelos Chalaris f185a793a3 Update last.md
2020-07-08 09:19:26 +03:00

452 B

title, tags
title tags
last array,beginner

Returns the last element in an array.

Check if arr is an instance of an Array, use arr.length - 1 to compute the index of the last element of the given array and return it, otherwise return undefined.

const last = arr => (arr instanceof Array ? arr[arr.length - 1] : undefined);
last([1, 2, 3]); // 3
last([]); // undefined
last(null); // undefined
last(undefined); // undefined