NeuroAgent

JavaScript Check Null Undefined Complete Guide

Learn how to properly check for null, undefined, and blank variables in JavaScript. Discover edge cases, best practices, and robust implementations for reliable variable validation.

Question

What is the standard JavaScript function to check for null, undefined, or blank variables? I’ve created this function to validate variable values, but I’m unsure if it covers all cases:

javascript
function isEmpty(val){
    return (val === undefined || val == null || val.length <= 0) ? true : false;
}

Does this implementation correctly handle all edge cases for checking if a variable has a value in JavaScript?

NeuroAgent

The JavaScript function you’ve created has several issues that prevent it from handling all edge cases correctly. Your isEmpty function doesn’t properly handle various data types and will throw errors in certain scenarios.

Let me analyze the problems with your current implementation:

  1. Redundant undefined check: The condition val === undefined is redundant because val == null already matches both null and undefined due to JavaScript’s type coercion.

  2. Length property errors: The val.length <= 0 check will throw errors for many data types that don’t have a length property, such as numbers, booleans, dates, and most objects.

  3. Missing edge cases: Your function doesn’t handle whitespace-only strings, empty arrays, empty objects, or special values like NaN.

Here’s an improved version that handles all these cases:

javascript
function isEmpty(val) {
    // Check for null, undefined, or empty string
    if (val == null || val === '') {
        return true;
    }
    
    // Check for string with only whitespace
    if (typeof val === 'string' && val.trim() === '') {
        return true;
    }
    
    // Check for arrays with length property
    if (Array.isArray(val) && val.length === 0) {
        return true;
    }
    
    // Check for empty objects (excluding arrays)
    if (typeof val === 'object' && val !== null && !Array.isArray(val) && 
        Object.keys(val).length === 0) {
        return true;
    }
    
    // Handle NaN specifically
    if (typeof val === 'number' && isNaN(val)) {
        return true;
    }
    
    return false;
}

Contents

Common Edge Cases and Solutions

1. Basic Null and Undefined Checks

javascript
// Simple check for null/undefined
if (val == null) {
    return true;
}

This single condition covers both null and undefined due to JavaScript’s loose equality rules.

2. String Validation

javascript
// Check for empty or whitespace-only strings
if (typeof val === 'string') {
    return val.trim() === '';
}

This handles both empty strings ("") and strings containing only whitespace.

3. Array Validation

javascript
// Check for empty arrays
if (Array.isArray(val)) {
    return val.length === 0;
}

Alternative Implementations

Comprehensive isEmpty Function

javascript
function isEmpty(val) {
    // Null/undefined check
    if (val == null) return true;
    
    // String check (including whitespace)
    if (typeof val === 'string') return val.trim() === '';
    
    // Array check
    if (Array.isArray(val)) return val.length === 0;
    
    // Object check (excluding arrays and null)
    if (typeof val === 'object' && val !== null && !Array.isArray(val)) {
        return Object.keys(val).length === 0;
    }
    
    // NaN check
    if (typeof val === 'number' && isNaN(val)) return true;
    
    // For other types, consider them non-empty
    return false;
}

Lodash-style Implementation

javascript
function isEmpty(val) {
    if (val == null) return true;
    
    if (typeof val === 'string' || Array.isArray(val)) {
        return val.length === 0;
    }
    
    if (typeof val === 'object') {
        return Object.keys(val).length === 0;
    }
    
    if (typeof val === 'number' && isNaN(val)) return true;
    
    return false;
}

Type-Specific Validation Functions

For more granular control, you might want separate functions for different types:

javascript
// Check if variable is null or undefined
function isNullish(val) {
    return val == null;
}

// Check if string is empty or whitespace
function isBlankString(str) {
    return typeof str === 'string' && str.trim() === '';
}

// Check if array is empty
function isEmptyArray(arr) {
    return Array.isArray(arr) && arr.length === 0;
}

// Check if object is empty
function isEmptyObject(obj) {
    return typeof obj === 'object' && obj !== null && 
           !Array.isArray(obj) && Object.keys(obj).length === 0;
}

Performance Considerations

  1. Order of checks: Place the most common checks first for better performance.

  2. Avoid unnecessary type checking: If you know the expected type, you can skip some checks.

  3. Object property access: Accessing Object.keys() has some overhead, so consider if you really need it.

Best Practices for Variable Validation

1. Be Specific About Your Needs

  • Do you need to distinguish between different types of “empty”?
  • Should false be considered empty?
  • Should 0 be considered empty?

2. Consider Using Libraries

Popular libraries like Lodash provide robust implementations:

javascript
// Using Lodash
import _ from 'lodash';

// Lodash's isEmpty handles all cases
_.isEmpty(val); // Returns true for null, undefined, "", [], {}, etc.

3. Document Your Validation Behavior

Always document what your function considers “empty” to avoid confusion:

javascript
/**
 * Checks if a value is considered "empty"
 * - Returns true for: null, undefined, '', [], {}, NaN
 * - Returns false for: false, 0, ' ', [1], {a: 1}
 * @param {*} val - The value to check
 * @returns {boolean} True if the value is empty, false otherwise
 */
function isEmpty(val) {
    // implementation
}

Testing Your Validation Function

Here’s how to test your function against various edge cases:

javascript
// Test cases
const testCases = [
    { input: null, expected: true, description: 'null' },
    { input: undefined, expected: true, description: 'undefined' },
    { input: '', expected: true, description: 'empty string' },
    { input: '   ', expected: true, description: 'whitespace string' },
    { input: [], expected: true, description: 'empty array' },
    { input: {}, expected: true, description: 'empty object' },
    { input: NaN, expected: true, description: 'NaN' },
    { input: false, expected: false, description: 'boolean false' },
    { input: 0, expected: false, description: 'number zero' },
    { input: 'hello', expected: false, description: 'non-empty string' },
    { input: [1, 2, 3], expected: false, description: 'non-empty array' },
    { input: { a: 1 }, expected: false, description: 'non-empty object' }
];

// Run tests
testCases.forEach(({ input, expected, description }) => {
    const result = isEmpty(input);
    const passed = result === expected;
    console.log(`${description}: ${passed ? '✓' : '✗'} (Expected: ${expected}, Got: ${result})`);
});

Your original function fails several of these tests and would throw errors for inputs like 0, false, or {}. The improved implementations above handle all these cases safely and consistently.

Sources

  1. MDN Web Docs - Equality comparisons and sameness
  2. MDN Web Docs - typeof operator
  3. MDN Web Docs - Object.keys()
  4. Lodash Documentation - isEmpty
  5. JavaScript.info - Type Conversions

Conclusion

Your original function has several critical flaws that make it unsafe for production use. The main issues include:

  1. Runtime errors when accessing .length on non-iterable types
  2. Redundant checks that don’t improve functionality
  3. Missing edge cases like whitespace strings, empty objects, and NaN

The improved implementations provided handle all common JavaScript data types safely and consistently. For production code, consider using established libraries like Lodash’s isEmpty() function, which has been thoroughly tested and optimized.

When implementing variable validation in JavaScript, always:

  • Handle all data types without throwing errors
  • Be clear about what constitutes “empty” in your context
  • Document your validation behavior
  • Test thoroughly against edge cases

Would you like me to elaborate on any specific aspect of variable validation or provide additional examples for particular use cases?