How to Check if an Object is Empty in JavaScript
Tags: javascript
Published: 2023-11-09 11:25:31

`How to... js series`

In JavaScript there is no default method or length property on the object, it is only available to arrays and strings that have the _length_ property. Nor _.size_ available for _Set_ objects. 

Besides that, using _equality operator_ to compare two objects, it compares their references in memory, not their contents. 

`code`
```javascript
const isEmptyObject = ({} === {}) // or equality operator ==
```

`test`
```javascript
test('should be empty or {}', () => {
 expect(isEmptyObject).toBeTruthy()
})
```

❌ `FAIL` should be empty or {}

Since here are two different objects, even if they have the same properties and values or none at all, the comparison will return false because they are not the same object in memory.

Loops (for...in) can solve this, but ECMAScript6 offers cleaner ways to check if an object is empty.

## ✨ Object.keys()

> The Object.keys() static method returns an array of a given object's own enumerable string-keyed property names.

➔ More detail about [**enumerable properties** and **own properties**](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties)

`code`
```javascript
const users = {'1': {name: 'alex'}}
const currentUser = {}
const isEmptyUser = Object.keys(currentUser).length === 0
const isEmptyList = Object.keys(users).length === 0
// or
// const isEmptyList = !Object.keys(users).length
```

`test`
```javascript
test('should be empty object', () => {
 expect(isEmptyUser).toBeTruthy()
})

test('should not be empty object', () => {
 expect(isEmptyList).toBeFalsy()
})
```

✅ `PASS` should be empty object
✅ `PASS` should not be empty object

It is possible achieve the same with `Object.values()` and `Object.entries()`

**NOTE:** When there is not guaranty that a value is an object is necessary validate the type to prevent _Uncaught TypeError_ using Object methods caused by **null** and **undefined**. Any other type returns an array as expected.

`code`
```javascript
const user;

// it is enough to prevent the error
if(user){
 const isEmptyList = !Object.keys(user).length
}
// or
isEmpty = (value)=> !(value && Object.keys(value).length)
isEmpty(user)
```
But validating before whether the value type is actually an Object makes more sense in some cases.

➔ More detail about [How to Check if a Value is an Object] ( https://dev.to/alesm0101/how-to-check-if-a-value-is-an-object-in-javascript-3pin)


## 🤐 JSON.stringify(): The ugly and unreliable way

> The JSON.stringify() static method converts a JavaScript value to a JSON string.

⚠️ **NOTE:** `undefined`, `function` and `Symbol` as value in object property are ignored

`code`
```javascript
const user = {}
const currentUser = { validId: (id) => id > 100 }
const isEmpty = JSON.stringify(user) === '{}'
const isEmptyUser = JSON.stringify(currentUser) === '{}'
```

`test`
```javascript
test('should be empty object', () => {
 expect(isEmpty).toBeTruthy()
})

test('should detect validId property', () => {
 expect(isEmptyUser).toBeFalsy()
})
```
✅ `PASS` should be empty object
❌ `FAIL` should detect validId property