Check if Object is empty in Javascript

Posted by

Unfortunately, there is no build-in isEmpty or similar method to checking if specific object is empty(has own properties) in JavaScript. We usually create our own helper method or use an external library like lodash. Although, these libraries are offering a lot of goodies, it is highly impractical to import them just for using one or two methods(like buying a Ferrari to drive to the supermarket).

My favorite way to check if a specific object is empty is using the Object.getOwnPropertyNames method.This method returns an array with all own properties of a specific object.

We can use this functionality to achieve our goal like this:

const obj = {};
Object.getOwnPropertyNames(obj).length === 0;
// [].length === 0  => true
const obj = { a: 2};
Object.getOwnPropertyNames(obj).length === 0;
// ["a"].length === 0 => false 

Or wrap it in a so called “helper” function, which will be used whenever needed.

function isEmpty(obj) {
  return Object.getOwnPropertyNames(obj).length === 0;
}

You can use this method in browsers that support ES5+

The other popular way to check if a specific object is empty, but is also compatible with older versions of the popular browsers is using for..in (check for compatibility info here)

function isEmpty(obj) {
    for(var prop in obj) {
        if(obj.hasOwnProperty(prop)) return false;
    }
    return true;
}

isEmpty({}); // true
isEmpty({a:5}); // false

Theoretically, this will result in a better performance than the previous method. When looping thru the object, it will return false right after the first own property, whereas the first one extracts all the properties and then check the length.

Both of the ways above works with empty objects – {} and objects containing own properties { a: 5 }. However, if you try to use this methods with different type of input, like “string”, both of them will result that this “string” is not empty.

If your intention is your helper method to work with different input types(not only objects), you will want to extend your logic. I would highly suggest you to take a look at the implementation of the popular lodash library – https://github.com/lodash/lodash/blob/master/isEmpty.js

As a library used by a million of developers, you can be sure that a lot edge cases are handled there and you don’t have to reinvent the wheel.

Conclusion

If you know that your input to the helper function will be always object(empty or not), then you can confidently go with any of the first two methods. In case you want your function to be more flexible and of course expect a different types as input parameters, explore the provided by lodash and adapt it to your use case.