Appearance
第1期 33 week 2024-08-16
While arrays and strings share a length property, objects don't have a direct way to determine their size. In order to do so, we can use Object.keys() to get an array of the object's keys and then check its length. Luckily, Object.keys() also works on arrays and string, returning their indices as strings.
Given this information, we can use Array.prototype.length to check if the resulting keys are empty. If the value is null or undefined, we can consider it empty as well
javascript
const isEmpty = val =>
val === null || val === undefined || !Object.keys(val).length;
isEmpty([]); // true
isEmpty([1, 2]); // false
isEmpty({}); // true
isEmpty({ a: 1, b: 2 }); // false
isEmpty(''); // true
isEmpty('text'); // false
isEmpty(null); // true
isEmpty(undefined); // true