Home ยป JavaScript ยป Check if Object is Not Empty in JavaScript

Check if Object is Not Empty in JavaScript

To check if an object is not empty in JavaScript, you can use the Object.keys() method to get an array of the object's own enumerable properties, and then check if the length of the array is greater than 0.

Check if Object is Not Empty in JavaScript Example

Here is an example of a complete program in JavaScript that demonstrates how to check if an object is not empty:

// Define an object with some properties
const obj = {
   foo: 'hello',
   bar: 'world',
   baz: 123
};

// Use the Object.keys() method to check if the object has own enumerable properties
if (Object.keys(obj).length > 0) {
   console.log('obj is not empty');
} else {
   console.log('obj is empty');
}

// Use the 'in' operator to check if the object has a property 'foo'
if ('foo' in obj) {
   console.log("obj has a property 'foo'");
} else {
   console.log("obj doesn't have a property 'foo'");
}

In this example, the obj object is defined with three properties: foo, bar, and baz. Then, the Object.keys() method is used to check if the object has any own enumerable properties, and the in operator is used to check if the object has a property foo.

If you run this program, the output would be:

obj is not empty
obj has a property 'foo'

This output shows that the obj object is not empty, and it has a property foo.

Note that this program only checks if the object has own enumerable properties, and not if it has inherited properties. For example, if you create another object that inherits from obj, like this:

const obj2 = Object.create(obj);

The obj2 object will inherit the properties of obj, but the Object.keys() method and the in operator will not consider these inherited properties when checking if obj2 is empty or has a property foo. To check for inherited properties, you would need to use a different approach, such as using the Object.getOwnPropertyNames() method or the Reflect.ownKeys() method.