As mentioned in a previous post, I really dislike lodash because when something can be implemented natively and efficiently, using lodash often just shows laziness and weak JS fundamentals. But if things are clear enough, using it appropriately is fine. After all, why reinvent the wheel?
Today I looked at the source code of isEmpty because I had some misunderstandings about this function. For example:
console.log(_.isEmpty(1)); // true
console.log(_.isEmpty('1')); // false
isEmpty
The official docs say:
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.
So it is mainly used to determine empty objects, collections, and array-like values.
Examples
console.log(_.isEmpty(null)); // true
console.log(_.isEmpty({})); // true
console.log(_.isEmpty('')); // true
console.log(_.isEmpty(undefined)); // true
console.log(_.isEmpty(1)); // true
Source Code
Let’s look at how these cases are judged in the source:
function isEmpty(value) {
if (value == null) {
return true // null, undefined return true
}
if (isArrayLike(value) &&
(Array.isArray(value) || typeof value === 'string' || typeof value.splice === 'function' ||
isBuffer(value) || isTypedArray(value) || isArguments(value))) {
return !value.length // '' returns true
}
const tag = getTag(value)
if (tag == '[object Map]' || tag == '[object Set]') {
return !value.size
}
if (isPrototype(value)) {
return !Object.keys(value).length
}
for (const key in value) {
if (hasOwnProperty.call(value, key)) {
return false
}
}
return true // number 1, {} return true
}
Details
- null == undefined
console.log(null==undefined); // true
console.log(null===undefined); // false
The equality check uses == instead of ===. Note that null == undefined is true. This is understandable since both mean empty values.
Object.prototype.toString()
The
getTagmethod mainly usesObject.prototype.toString(value).The official docs say the
toString()method returns a string representing the object.const a={}; console.log(a.toString()); \\ [object Object]

