7

I ran across this case today

if ({}) {
  // This is returned as empty object is true
}

therefore need to figure out a way where {} is false, tried calling .length on an object I pass to the if statement, but that doesn't work.

Ilja
  • 44,142
  • 92
  • 275
  • 498

2 Answers2

8

You can use Object.keys() method to achieve this.

From Mozilla's Documentation:

The Object.keys() method returns an array of a given object's own enumerable properties, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).

if (Object.keys({}).length) {
  console.log('Object is not Empty');
} else {
  console.log('Object is Empty');
}

console.log(Object.keys({}).length);
Mohammad Usman
  • 37,952
  • 20
  • 92
  • 95
2

You can try to use:

Object.keys(obj).length === 0;
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331