Ricky Ricky - 9 months ago 36
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?


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.