Skip to main content

IsEmpty Function

Validation7 functions

Utility Overview

Details

Comprehensive emptiness checking for all JavaScript data types including objects, arrays, strings, and collections

Category:Validation
Functions:isEmpty, isEmptyStrict, isEmptyDeep, isEmptyString, isEmptyArray, isEmptyObject, isEmptyCollection
Concepts:
type guardstype checkingdata validationtruthiness

Implementation

isEmpty

Time: O(1) | Space: O(1)
export function isEmpty(value: unknown): boolean {
  // Null and undefined
  if (value == null) return true;
  
  // Primitive types (boolean, number, symbol)
  if (typeof value === 'boolean') return false;
  if (typeof value === 'number') return value === 0 || Number.isNaN(value);
  if (typeof value === 'symbol') return false;
  if (typeof value === 'bigint') return value === BigInt(0);
  
  // String
  if (typeof value === 'string') return value.length === 0 || value.trim().length === 0;
  
  // Array
  if (Array.isArray(value)) return value.length === 0;
  
  // Map and Set
  if (value instanceof Map || value instanceof Set) return value.size === 0;
  
  // Date
  if (value instanceof Date) return false;
  
  // Object (including plain objects)
  if (typeof value === 'object') {
    // Check for own enumerable properties
    return Object.keys(value).length === 0;
  }
  
  // Function
  if (typeof value === 'function') return false;
  
  return true;
}

// Strict isEmpty that considers whitespace-only strings as non-empty

Usage Examples

Basic emptiness validation

// Primitive types
isEmpty(null);           // true
isEmpty(undefined);      // true
isEmpty('');            // true
isEmpty('   ');         // true (whitespace)
isEmpty(0);             // true
isEmpty(NaN);           // true
isEmpty(false);         // false

// Collections
isEmpty([]);            // true
isEmpty({});            // true
isEmpty(new Map());     // true
isEmpty(new Set());     // true

// Non-empty values
isEmpty('hello');       // false
isEmpty([1, 2, 3]);     // false
isEmpty({ key: 'value' }); // false

Form field validation

interface FormData {
  username: string;
  email: string;
  preferences: string[];
}

function validateForm(data: FormData): string[] {
  const errors: string[] = [];
  
  if (isEmpty(data.username)) {
    errors.push('Username is required');
  }
  
  if (isEmpty(data.email)) {
    errors.push('Email is required');
  }
  
  if (isEmptyArray(data.preferences)) {
    errors.push('At least one preference must be selected');
  }
  
  return errors;
}

const formData = { username: '', email: 'user@example.com', preferences: [] };
const errors = validateForm(formData); // ['Username is required', 'At least one preference must be selected']

Deep emptiness validation for nested data

const data = {
  user: {
    profile: {
      name: '',
      settings: {}
    },
    posts: []
  },
  metadata: {
    tags: [],
    categories: {}
  }
};

isEmpty(data);         // false (has keys)
isEmptyDeep(data);     // true (all nested values are empty)

// Practical use case
function hasContent(obj: unknown): boolean {
  return !isEmptyDeep(obj);
}

hasContent({ a: { b: { c: '' } } });  // false
hasContent({ a: { b: { c: 'value' } } }); // true

API response content validation

interface ApiResponse {
  data: unknown[];
  metadata: Record<string, unknown>;
  errors: string[];
}

function processApiResponse(response: ApiResponse) {
  if (isEmptyArray(response.data)) {
    return { status: 'no-data', message: 'No data available' };
  }
  
  if (!isEmptyArray(response.errors)) {
    return { status: 'error', errors: response.errors };
  }
  
  if (isEmptyObject(response.metadata)) {
    console.warn('Response missing metadata');
  }
  
  return { status: 'success', data: response.data };
}

const response = { data: [], metadata: {}, errors: [] };
processApiResponse(response); // { status: 'no-data', message: 'No data available' }

Ā© 2025 John Dilig. Built with Next.js & TypeScript. Open Source (MIT) • Wiki

v... • Auto-versioned