Check Object is Empty JavaScript

To check an object is empty in JavaScript use the Object.keys() function and check its length is equal to 0.

 

Check for Empty Object JavaScript Example

In the example below the code in the if block will run if the evaluated object is empty:

 

var obj = {}

if (obj && Object.keys(obj).length === 0) {
  console.log('Object is defined and empty.');
}

 

In the example above the first obj in the if statement is to check the object is defined and not equal to null.

 

Check an Object is Empty in jQuery

If you're using jQuery you can use the isEmptyObject() function, which provides a cleaner syntax. Pass the object as the first argument of isEmptyObject() and it will return true if it is empty.

 

var obj = {}

if ($.isEmptyObject(obj)) {
  console.log('Object is defined and empty.');
}