if(user)
will pass for empty Object/Array, but they are empty and should be rejected.
Also if(user)
will fail for values like 0
or false
which are totally valid values.
Using isEmpty()
will take care of such values. Also, it makes code more readable.
Point to note is isEmpty(1)
will return true
as 1
is a primitive value and not a data structure and hence should return true
.
This has been stated in Docs:
Checks if value is an empty object, collection, map, or set.
Also as per docs,
Objects are considered empty if they have no own enumerable string keyed properties.
So if you have an object which does not have non-enumerable properties, its considered as empty. In the below example, foo
is a part of object o
and is accessible using o.foo
but since its non-enumerable, its considered as empty as even for..in
would ignore it.
var o = Object.create(null);
Object.defineProperty(o, "foo", {
enumerable: false,
value: "Hello World"
})
Object.defineProperty(o, "bar", {
enumerable: false,
value: "Testing 123"
});
console.log(o)
for (var k in o) {
console.log(k)
}
console.log(o.foo)
console.log(_.isEmpty(o))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
Note: This does not mean you should use lodash for such purpose. You can write your own isEmpty
function.
Following is something that I use:
This will return true for following cases:
{}
, []
, ""
, undefined
, null
, object in above snippet(no enumerable property)
function isEmpty(value){
return value === undefined ||
value === null ||
(typeof value === "object" && Object.keys(value).length === 0) ||
(typeof value === "string" && value.trim().length === 0)
}