Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle empty object in if statement as false? [duplicate]

Tags:

javascript

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.

like image 606
Ilja Avatar asked Jul 04 '16 11:07

Ilja


People also ask

How do you condition an empty object?

keys method to check for an empty object. const empty = {}; Object. keys(empty). length === 0 && empty.

Is Empty object truthy or Falsy?

Values not on the list of falsy values in JavaScript are called truthy values and include the empty array [] or the empty object {} . This means almost everything evaluates to true in JavaScript — any object and almost all primitive values, everything but the falsy values.

How can you tell if an object is not empty?

Use Object. Object. keys will return an array, which contains the property names of the object. If the length of the array is 0 , then we know that the object is empty.

Is Empty Falsy?

A falsy value is something which evaluates to FALSE, for instance when checking a variable. There are only six falsey values in JavaScript: undefined , null , NaN , 0 , "" (empty string), and false of course.


2 Answers

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);
like image 94
Mohammad Usman Avatar answered Oct 01 '22 17:10

Mohammad Usman


You can try to use:

Object.keys(obj).length === 0;
like image 42
Rahul Tripathi Avatar answered Oct 01 '22 15:10

Rahul Tripathi