How to Check If an Object is Empty in JavaScript

To check if an Object is empty in JavaScript, you can use the “Object.keys()” method, which returns an array of the Object’s property names, and check if the length of the returned array is 0, which suggests that the Object has no properties.

Example

function isEmptyObject(obj) {
  return Object.keys(obj).length === 0;
}

const emptyObject = {};
const nonEmptyObject = { name: 'Niva Shah', age: 30 };

console.log(isEmptyObject(emptyObject));
console.log(isEmptyObject(nonEmptyObject));

Output

true
false

In this code example, we defined a custom function isEmptyObject(), that takes an object as its argument.

The custom function uses the Object.keys() function to get an array of the Object’s property names and checks if the array’s length is 0. If the length is 0, the function returns true, suggesting that the Object is empty; otherwise, it returns false.

Leave a Comment