DEV Community

Alex M
Alex M

Posted on • Updated on

How to Check if an Object is Empty in JavaScript

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

const isEmptyObject = ({} === {}) // or equality operator ==
Enter fullscreen mode Exit fullscreen mode

test

test('should be empty or {}', () => {
 expect(isEmptyObject).toBeTruthy()
})
Enter fullscreen mode Exit fullscreen mode

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

code

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
Enter fullscreen mode Exit fullscreen mode

test

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

test('should not be empty object', () => {
 expect(isEmptyList).toBeFalsy()
})
Enter fullscreen mode Exit fullscreen mode

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

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)
Enter fullscreen mode Exit fullscreen mode

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

🤐 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

const user = {}
const currentUser = { validId: (id) => id > 100 }
const isEmpty = JSON.stringify(user) === '{}'
const isEmptyUser = JSON.stringify(currentUser) === '{}'
Enter fullscreen mode Exit fullscreen mode

test

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

test('should detect validId property', () => {
 expect(isEmptyUser).toBeFalsy()
})
Enter fullscreen mode Exit fullscreen mode

PASS should be empty object
FAIL should detect validId property

Top comments (0)