Files
30-seconds-of-code/snippets/head.md
Isabelle Viktoria Maciohsek c2fdfac6ce Re-tag array snippets
2020-10-18 14:58:09 +03:00

20 lines
397 B
Markdown

---
title: head
tags: array,beginner
---
Returns the head of an array.
- 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
```