Check if a JavaScript object is empty.

This is a tutorial on how to check if a JavaScript object is empty or not. In this guide, I will provide you with a custom JavaScript function that is compatible with older browsers such as Internet Explorer.

Take a look at the following function:

The JavaScript function above takes in an object as a parameter before checking to see whether it is empty or not. If the object is empty, this function will return a boolean TRUE value. If the object is not empty, then it will return a FALSE value.

This function essentially loops through the object while checking to see if a property exists. If an object property is found, then the function returns a TRUE value. This return statement also halts any further iterations of the for loop.

You can test this function out with the following code snippet:

Here, we created two JavaScript objects. The first object is empty and the second one is not empty. If you pass these objects into our custom JavaScript function, you will see that it returns TRUE for the first object and FALSE for the second object.

Using Object.keys()

A few tutorials recommend using the Object.keys() method, which became available in ECMA 5+:

The code above assumes that if Object.keys() returns an empty array, then the object in question is empty.

The problem with Object.keys() is that it is not supported by older browsers such as Internet Explorer 8.

This method is also “O(n) time complexity”, which essentially means that it will become slower and slower with larger objects. The reason for this is that Object.keys() has to return an array of the object’s keys before the length can be checked, whereas the method used in the first example will break out of the loop as soon as a key is discovered.

Using jQuery to check if an object is empty.

The jQuery library comes equipped with its own method, which is called jQuery.isEmptyObject(). This method will return TRUE if the object in question is empty:

If you run the code snippet above, you will see that it detects our empty object.

Facebook Comments