This post will discuss how to check for an empty object in JavaScript.

There are several ways to create an empty object in JavaScript, such as:

let obj = new Object();
let obj = new Object(undefined);
let obj = new Object(null);
let obj = {};

To check if the object is empty in JavaScript, we can use any of the following functions:

1. Using Object.entries() function

The Object.entries() function returns an array of the own property [key, value] pairs of an object. We can also check the length of this array to determine if the object has any own properties. We can use this as:

Download  Run Code

 
This function is simple and fast, but it will also return true for objects having non-enumerable properties or inherited properties. For example, the above code would return true for a Date object. However, this can be handled by placing an additional check:

Download  Run Code

 
Similar to the Object.entries() function, we can also use the Object.keys() or Object.values() function. The Object.keys() returns an array of the own property names of an object and Object.values() function returns an array of the own property values of an object. We can check the length of the returned array to determine if the object has any own properties.

Download  Run Code

2. Using third-party libraries

If jQuery is already used in the project, we can use the $.isEmptyObject() function to determine whether an object is empty. It returns true if the object has no properties of its own, and false otherwise. However, it returns true for date object, null, and undefined values. The following code example demonstrates its usage:

Download Code

 
Alternatively, we can use the _.isEmpty() function from the lodash or underscore library. It returns true if the value is an empty object, collection, map, or set. Like $.isEmptyObject(), it also returns true for date object, null, and undefined values.

Download Code

3. Using JSON.stringify() function

Finally, we can convert the given object into a string using the JSON.stringify() function and compare the string representation of the object against {} to determine whether it is empty. This solution works for most cases, but fails when the object contains functions. Here’s an example of this approach:

Download  Run Code

That’s all about determining whether an object is empty in JavaScript.