Aller au contenu principal

isEmpty()

isEmpty(value): boolean

Checks if value is empty (object, array, string, Map, or Set).

remarque

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

ValueResult
[] 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));
}