Files
30-seconds-of-code/snippets/isEmpty.md
Chalarangelo 6c258ab420 Update isEmpty
Use collection instead of array, as the snippet works for objects.
2022-07-22 12:37:58 +03:00

28 lines
773 B
Markdown

---
title: Collection is empty
tags: type,array,object,string
expertise: beginner
cover: blog_images/book-chair.jpg
firstSeen: 2018-01-23T19:25:17+02:00
lastUpdated: 2020-10-20T23:02:01+03:00
---
Checks if the a value is an empty object/collection, has no enumerable properties or is any type that is not considered a collection.
- Check if the provided value is `null` or if its `length` is equal to `0`.
```js
const isEmpty = val => val == null || !(Object.keys(val) || val).length;
```
```js
isEmpty([]); // true
isEmpty({}); // true
isEmpty(''); // true
isEmpty([1, 2]); // false
isEmpty({ a: 1, b: 2 }); // false
isEmpty('text'); // false
isEmpty(123); // true - type is not considered a collection
isEmpty(true); // true - type is not considered a collection
```