How to Check if an Object is Empty Using jQuery

This guide explains how to determine whether a JavaScript object contains any properties using jQuery's built-in $.isEmptyObject() method. You will learn the syntax, see practical code examples demonstrating both empty and populated objects, and understand how the method handles different data types and edge cases.

Syntax and Basic Usage

The $.isEmptyObject() method checks whether an object has any enumerable properties. It accepts a single argument and returns a boolean value: true if the object has no properties of its own, or false if it contains at least one property.

$.isEmptyObject(object);

Checking Plain Objects

When passed a standard object literal, the method returns true if it has no keys, and false if properties are present:

// An empty object
const emptyObj = {};
console.log($.isEmptyObject(emptyObj)); // Output: true

// An object with properties
const user = { name: "Alice", age: 30 };
console.log($.isEmptyObject(user)); // Output: false

// An object with an undefined value still counts as not empty
const objWithUndefined = { key: undefined };
console.log($.isEmptyObject(objWithUndefined)); // Output: false

How It Works Internally

Under the hood, $.isEmptyObject() utilizes a standard for...in loop to iterate over the object's properties:

isEmptyObject: function( obj ) {
    for ( var name in obj ) {
        return false;
    }
    return true;
}

Because the for...in loop only executes if there is an enumerable property to iterate over, the function immediately returns false on the first property found. If the loop completes without executing, it returns true.

Handling Arrays and Other Data Types

Because arrays and primitive types behave in specific ways within a for...in loop, $.isEmptyObject() produces the following results when tested with non-object values:

  • Arrays: An empty array [] returns true. An array with elements [1, 2] returns false.
  • Null and Undefined: Both $.isEmptyObject(null) and $.isEmptyObject(undefined) return true.
  • Strings: An empty string "" returns true, while any non-empty string "text" returns false because characters in a string act as enumerable indices.
  • Numbers and Booleans: Values like 100 or false return true because primitive numbers and booleans have no enumerable properties.

Vanilla JavaScript Alternative

If you want to achieve the same result without relying on jQuery, you can use the native Object.keys() method:

function isObjectEmpty(obj) {
    return obj && Object.keys(obj).length === 0 && obj.constructor === Object;
}

Using Object.keys(obj).length === 0 provides the modern ECMAScript standard equivalent for checking object emptiness without third-party libraries.