Posted inJavaScript / jQuery

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).

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

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.

I am Jaydeep Gondaliya , a software engineer, the founder and the person running Pakainfo. I'm a full-stack developer, entrepreneur and owner of Pakainfo.com. I live in India and I love to write tutorials and tips that can help to other artisan, a Passionate Blogger, who love to share the informative content on PHP, JavaScript, jQuery, Laravel, CodeIgniter, VueJS, AngularJS and Bootstrap from the early stage.

Leave a Reply

Your email address will not be published. Required fields are marked *

We accept paid guest Posting on our Site : Guest Post Chat with Us On Skype