isEmpty()
isEmpty(
value):boolean
Checks if value is empty (object, array, string, Map, or Set).
note
Primitives (numbers, booleans) and null/undefined return true.
Parametersโ
value: unknownโ
The value to check.
Returns: booleanโ
true if value is empty, false otherwise.
Sinceโ
2.0.0
Performanceโ
O(1) for primitives/null/undefined/arrays/strings/Map/Set via early returns and native properties. O(n) for objects due to Object.keys().
Exampleโ
isEmpty([]); // => true
isEmpty([1, 2]); // => false
isEmpty({}); // => true
isEmpty({ a: 1 }); // => false
isEmpty(''); // => true
isEmpty('abc'); // => false
isEmpty(new Map()); // => true
isEmpty(new Set([1])); // => false
isEmpty(null); // => true
isEmpty(42); // => true (primitives are "empty")
How it works?โ
Checks if a value is empty (arrays, objects, strings, Map, Set).
Examplesโ
| Value | Result |
|---|---|
[] | true |
[1, 2] | false |
{} | true |
{ a: 1 } | false |
'' | true |
'abc' | false |
new Map() | true |
new Set([1]) | false |
null | true |
42 | true (primitives are "empty") |
Use Case: Form Validationโ
Use Casesโ
Check for empty collections ๐โ
Verify if an array, object, string, or collection is empty. Essential for validating data completeness before processing.
if (isEmpty(data)) {
return null; // Handle empty state
}
Validate form inputsโ
Ensure required fields are not empty strings. Critical for user input validation.
if (isEmpty(username.trim())) {
showError("Username is required");
}
Guard against processing empty dataโ
Early return when collections have no items to process. Prevents unnecessary operations and potential errors.
function sendNotifications(users: User[]) {
if (isEmpty(users)) {
console.log("No users to notify");
return;
}
// Safe to process - we have users
users.forEach(user => notify(user));
}
true
false