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
  • 40,784
  • 74
  • 242
  • 455

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
  • 34,173
  • 19
  • 88
  • 85
2

You can try to use:

Object.keys(obj).length === 0;
Rahul Tripathi
  • 161,154
  • 30
  • 262
  • 319