Ricky Ricky - 4 months ago 13
Javascript Question

How to check if object has any properties in JavaScript?

Assuming I declare

var ad = {};


How can I check whether this object will contain any user-defined properties?

Answer

You can loop over the properties of your object as follows:

for(var prop in ad) {
    if (ad.hasOwnProperty(prop)) {
        // handle prop as required
    }
}

It is important to use the hasOwnProperty() method, to determine whether the object has the specified property as a direct property, and not inherited from the object's prototype chain.

Comments