Skip to content

Different ways to check if an Object is empty using JavaScript

Today we are going to see the different methods to find the object that we using is empty or not. This is not that much easy to check the object is empty like Array.length() method, Object do not work that way.

Let’s take the below empty Object which is not initialized with key and value,

let obj = {};

1. Object.keys()

ES6 Version, this returns the array of key values in Object. We can check with the length of returned array like below.

Object.keys(obj).length === 0; // Returns true

We can also use the methods Object.values and Object.entries(ES7). These are most easiest way to check if the Object is empty.

2. Pre-ECMA 5

Using traditional method for..in we can loop over the object to check it is empty or not like below,

function isEmpty(obj) {
  for(var prop in obj) {
      return false;
  }
}

This is one of the fasted method to find the empty object check.

3. JSON.stringify()

We can simply convert the Object to String and the result is simply an opening and closing bracket.

JSON.stringify(obj) === '{}'; // Returns true

4. Using Underscore and Lodash

_.isEmpty(obj);

5. isEmptyObject()

jQuery have special function isEmptyObject() for this case,

jQuery.isEmptyObject(obj); // Returns true

See also  How to remove a property from an object in JavaScript?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.