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.

3
  • I'm not sure what you're asking. If you want to find out if an object has no properties, use Object.keys. Commented Jul 4, 2016 at 11:16
  • You sort of have to define what "empty object" means. That is has no own keys...? Commented Jul 4, 2016 at 11:16
  • Object.keys(obj).length > 0 Commented Jul 4, 2016 at 11:16

2 Answers 2

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);

Sign up to request clarification or add additional context in comments.

Comments

2

You can try to use:

Object.keys(obj).length === 0;

1 Comment

You need to check for Symbols too

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.