Assuming I declare
var ad = {};
How can I check whether this object will contain any user-defined properties?
You can use the following:
Double bang !! property lookup
var a = !![]; // true
var a = !!null; // false
hasOwnProperty This is something that I used to use:
var myObject = {
name: 'John',
address: null
};
if (myObject.hasOwnProperty('address')) { // true
// do something if it exists.
}
However, JavaScript decided not to protect the method’s name, so it could be tampered with.
var myObject = {
hasOwnProperty: 'I will populate it myself!'
};
prop in myObject
var myObject = {
name: 'John',
address: null,
developer: false
};
'developer' in myObject; // true, remember it's looking for exists, not value.
typeof
if (typeof myObject.name !== 'undefined') {
// do something
}
However, it doesn't check for null.
I think this is the best way.
in operator
var myObject = {
name: 'John',
address: null
};
if('name' in myObject) {
console.log("Name exists in myObject");
}else{
console.log("Name does not exist in myObject");
}
result:
Name exists in myObject
Here is a link that goes into more detail on the in operator: Determining if an object property exists