lodash isEmpty and has method vs simple check
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 variable and not a datastructure 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.
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)}
Simple and elegant function for checking the values are empty or not
function isEmpty(value) { const type = typeof val; if ((value !== null && type === 'object') || type === 'function') { const properties = Object.keys(value); if (properties.length === 0 || properties.size === 0) { return true; } } return !value;}
Testing the above method
It will return 'true' for all cases below
console.log(isEmtpy(null)) console.log(isEmtpy(0))console.log(isEmtpy({}))console.log(isEmtpy(new Set())console.log(isEmtpy(Object.create(null))console.log(isEmtpy(''))console.log(isEmtpy(() => {}))console.log(isEmtpy(() => [])