How to Check if a Javascript Object Is Empty?

javascript

There are various methods to check if a JavaScript object is empty:

Method 1: Checking the length of Object.keys()

The Object.keys() method returns an array of all the properties of an object, and by checking the length of the array we can determine if the object is empty.

Example:

const obj = { };
if (Object.keys(obj).length === 0) {
   console.log("The object is empty");
} else {
   console.log("The object is not empty");
}

Method 2: Using the Object.entries() method

The Object.entries() method returns an array of key-value pairs of an object i.e the properties and values of the object. By checking the length of the array returned, we can determine if the object is empty.

Example:

const obj = { };
if (Object.entries(obj).length === 0) {
   console.log("The object is empty");
} else {
   console.log("The object is not empty");
}

Method 3: Using the for...in loop

We can use a for...in loop to iterate over all the properties of an object, and if no property is found, we can determine that the object is empty.

Example:

const obj = { };
let isEmpty = true;

for (let prop in obj) {
   isEmpty = false;
   break;
}

if (isEmpty) {
   console.log("The object is empty");
} else {
   console.log("The object is not empty");
}

All three methods are equally valid and can be used based on the requirement and preference.

Latest Questions

javascript How to Check if a Javascript Array Includes a Given Value? javascript How to Completely Uninstall Nodejs, and Reinstall From Scratch on Mac OS X? javascript How to Map Values of a Javascript Object to a New Object Using a Function?