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.
keys method to check for an empty object. const empty = {}; Object. keys(empty). length === 0 && empty.
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.
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.
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.
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 afor-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);
You can try to use:
Object.keys(obj).length === 0;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With