Files
30-seconds-of-code/snippets/last.md
Angelos Chalaris f8325eabd8 Update last.md
2019-12-11 09:52:33 +02:00

20 lines
458 B
Markdown

---
title: last
tags: 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 return it, otherwise return `undefined`.
```js
const last = arr => (arr && arr.length ? arr[arr.length - 1] : undefined);
```
```js
last([1, 2, 3]); // 3
last([]); // undefined
last(null); // undefined
last(undefined); // undefined
```