Q:

How to Test For an Empty Object in JavaScript

0

How to Test For an Empty Object in JavaScript

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Use the Object.keys() Method

You can simply use the Object.keys() method along with the typeof operator to test for an empty JavaScript object (contains no enumerable properties). Also, since null == undefined is true,
obj != null will catch both null and undefined values.

The isEmptyObject() function in the following example will check if an object is empty. However, it will only test plain objects (created using "{}" or "new Object()").

// Defining a function
function isEmptyObject(obj) {
    if(typeof obj === 'object' && obj != null && Object.keys(obj).length !== 0){
        return false;
    } else {
        return true;
    }
}

// Testing few values    
console.log(isEmptyObject({})); // Prints: true
console.log(isEmptyObject({name: "Harry", age: 18})); // Prints: false
console.log(isEmptyObject(null)); // Prints: true
console.log(isEmptyObject(undefined)); // Prints: true

If you're using jQuery you can simply use the jQuery.isEmptyObject() method to check if an object is empty. Let's try out an example to understand how it basically works:

// Testing few values    
console.log(jQuery.isEmptyObject({})); // Prints: true
console.log(jQuery.isEmptyObject({name: "Harry", age: 18})); // Prints: false
console.log(jQuery.isEmptyObject(null)); // Prints: true
console.log(jQuery.isEmptyObject(undefined)); // Prints: true

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

JavaScript / jQuery Frequently Asked Questions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to Check If a Key Exists in a JavaScript Objec... >>
<< How to Add a Key/Value Pair to an Object in Javasc...