2

With Lodash and Underscore I can know if an object is empty.

const a = {};

What I want to understand is why it doesn't recognize as empty an object where all its properties are undefined.

Example:

const a = {
  b: undefined,
  c: undefined
};

This question is not a duplicate of lodash: check object is empty: I am not looking for a method to validate if it is empty with undefined properties, I want to understand why even with properties of undefined value it is not an empty object.

Federico Grandi
  • 6,785
  • 5
  • 30
  • 50
ccordon
  • 1,072
  • 12
  • 22

2 Answers2

3

Your Object a is not empty, it has 2 properties defined on it, b and c and their values are undefined.

You say in one of your comments:

I understand perfectly that if it has properties but if its properties have no value, why not say that the object is empty.

But the thing is, those properties do not "have no value", they have the value undefined. undefined is a perfectly valid value just like null, "" (empty String), and NaN.

zero298
  • 25,467
  • 10
  • 75
  • 100
1

Your Question is answered in the docs you linked. If the functions are called on objects, they check the length. If length > 0, the object is not considered empty.

const a = {
  b: undefined,
  c: undefined
};

console.log(Object.keys(a).length); // 2

Underscore Docs

Returns true if an enumerable object contains no values (no enumerable own-properties). For strings and array-like objects _.isEmpty checks if the length property is 0.

Lodash Docs

Checks if value is an empty object, collection, map, or set.

Objects are considered empty if they have no own enumerable string keyed properties.

Array-like values such as arguments objects, arrays, buffers, strings, or jQuery-like collections are considered empty if they have a length of 0. Similarly, maps and sets are considered empty if they have a size of 0.

For that, imagine a file cabinet representing your object. While there may be nothing contained by the drawers, physically, the cabinet still contains the three drawers themselves. Depending on the context in which you use _.isEmpty(), this might or might not be an important piece of information.

enter image description here

Community
  • 1
  • 1
Tom M
  • 2,815
  • 2
  • 20
  • 47