How do I check if a value is an empty object in JavaScript without using Object.keys()?
Rashid D
rashid d profile pic

To check if a value is an empty object in JavaScript without usingObject.keys(), you can utilize theObject.getOwnPropertyNames() method combined with theArray.length property. Here's an example of how you can implement it:

1
2
3
4

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

In the above code, theisEmptyObject function takes an object as an argument. It uses theObject.getOwnPropertyNames() method to retrieve an array of all properties (including non-enumerable ones) of the object. Then, it checks the length of the array. If the length is 0, it means the object is empty. Here's an example of how you can use theisEmptyObject function:

1
2
3
4
5
6

const obj1 = {}; // empty object
const obj2 = { name: 'John', age: 30 }; // non-empty object

console.log(isEmptyObject(obj1)); // Output: true
console.log(isEmptyObject(obj2)); // Output: false

In this example,isEmptyObject is used to check ifobj1 andobj2 are empty objects. The function returnstrue forobj1 since it doesn't have any properties, while it returnsfalse forobj2 since it has properties. By usingObject.getOwnPropertyNames() in conjunction withArray.length, you can determine if an object is empty without relying onObject.keys().