When dealing with own property:
var assets = { value: 500 };
if(Object.prototype.hasOwnProperty.call(assets, "value"))
{
// This block will be executed
}
Note: It is recommended to use Object.prototype.hasOwnProperty instead of asset.hasOwnProperty(..), in case a custom hasOwnProperty is defined in the prototype chain (similar to the example below), like
var obj = {
hasOwnProperty: function() {
return false;
},
item: 'Custom object'
};
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty
If you need to consider inherited properties in the search, use the in operator: (make sure the right side of 'in' is an object, primitive values will cause errors, e.g. 'length' in 'house' will throw error, but 'length' in new String('house') won't)
const ninja = { hide: true };
const samurai = { attack: true };
const pirate = { sneak: true };
if ("hide" in ninja)
console.log("Ninja can hide");
if (!("attack" in ninja))
console.log("Ninja cannot attack");
if (!("sneak" in ninja))
console.log("Ninja cannot sneak");
Object.setPrototypeOf(ninja, samurai);
if ("attack" in ninja)
console.log("Ninja can now attack");
if (!("sneak" in samurai))
console.log("Samurai cannot sneak");
Object.setPrototypeOf(samurai, pirate);
if ("sneak" in samurai)
console.log("Samurai can now sneak");
if ("sneak" in ninja)
console.log("Ninja can also sneak");
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in
Note: Avoid using typeof and [ ] property accessor as shown in this code snippet which may not work as expected ...
var assets = { value: 500 };
assets.debt = undefined;
if("debt" in assets) // correct
{
// This block will execute
}
if(typeof assets["debt"] !== "undefined") // incorrect
{
// This block will not execute
}