Files
30-seconds-of-code/snippets/head.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

21 lines
392 B
Markdown

---
title: head
tags: array,beginner
---
Returns the head of a list.
Check if `arr` is truthy and has a `length` property, use `arr[0]` if possible
to return the first element, otherwise return `undefined`
```js
const head = arr => (arr && arr.length ? arr[0] : undefined);
```
```js
head([1, 2, 3]); // 1
head([]); // undefined
head(null); // undefined
head(undefined); // undefined
```