Since JavaScript allows you to create dynamic objects, you have to be careful and check if an object’s property actually exists. There are at least 2 ways to do this.
hasOwnProperty
hasOwnProperty
is a function built into all objects.
if (obj.hasOwnProperty('prop')) {
// do something
}
Note: Internet Explorer host objects (objects supplied by the environment and are different between browsers) do not have the hasOwnProperty
function.
in Operator
in
is a built in operator you can use to check for an existence of an object property.
if ('prop' in obj) {
// do something
}
Note: obj
‘s prorotypes will also be checked for the prop
property.
Undefined Check
You can check if an object has a property by checking if it’s undefined
:
if (typeof obj.prop !== 'undefined') {
// do something
}
or:
if (typeof obj['prop'] !== 'undefined') {
// do something
}
You have to use triple equals so that it won’t check for other falsy values.