how to check object is empty in javascript?

how to check object is empty in javascript? – We can use the built-in Object. Using the Object.keys(object) method and Looping through the object using object.hasOwnProperty(key).

Free Live Chat for Any Issue

how to check object is empty in javascript?

The JSON.stringify method is used to convert a JavaScript object to a JSON string. The keys method returns an array that contains an array of property names of the object under consideration.

How to check if JavaScript Object is empty?

check if an object is empty is by using a utility function

function isEmpty(obj) {
    for(var key in obj) {
        if(obj.hasOwnProperty(key))
            return false;
    }
    return true;
}

using the above function.

var lObject = {}; // Empty Object
if(isEmpty(lObject)) {
    //Your Object is empty (Would return true in this example)
} else {
    //Your Object is NOT empty
}

Alternatively

Object.prototype.isEmpty = function() {
    for(var key in this) {
        if(this.hasOwnProperty(key))
            return false;
    }
    return true;
}

Don’t Miss : Javascript Check If Object Is Empty

Also Read This πŸ‘‰   password strength checker jquery Example

check if the object is empty

var lObject = {
    myKey: "loveCalc"
}

if(lObject.isEmpty()) {
    // Your Object is empty
} else {
    // Your Object is NOT empty (would return false in this example)
}

I hope you get an idea about how to check object is empty in javascript.
I would like to have feedback on my infinityknow.com.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.

Rate this post