I am actually not sure if I just stumbled upon an unwanted behavior in javascript or if this is somehow intended behavior.
The following code results in a true statement:
var test= {"test":1}
document.write("constructor" in test);
http://jsfiddle.net/xyatxm2g/2/
If I change it to the following code, it returns false as it should:
var test= {"test":1}
document.write(test.hasOwnProperty("constructor"));
http://jsfiddle.net/fg06ovvc/2/
There are mainly two methods to check the existence of a key in JavaScript Object. The first one is using “in operator” and the second one is using “hasOwnProperty() method”. Method 1: Using 'in' operator: The in operator returns a boolean value if the specified property is in the object.
In the nutshell, Object in JavaScript is just key-value pairs stored in a Hash. The difference between property and method is that -- property is a value stored in the hash key, whereas method is a function stored in hash key.
JavaScript provides you with three common ways to check if a property exists in an object: Use the hasOwnProperty() method. Use the in operator. Compare property with undefined .
The hasOwnProperty
method, as the name says, look into the object to see if it has the property itself.
But when you use 'propertyName' in test
, you're not only looking into the object's own properties, but also the properties that come from inheritance.
In that case, constructor
is a property that resides inside the Object
's prototype, so all objects have that property, because they all inherit from Object
.
Quote from MDN
Every object descended from Object inherits the hasOwnProperty method. This method can be used to determine whether an object has the specified property as a direct property of that object; unlike the
in
operator, this method does not check down the object's prototype chain.
From the MDN documentation:
Inherited properties
The in operator returns true for properties in the prototype chain."toString" in {}; // returns true
Whereas the hasOwnProperty()
method only checks for properties directly on the object, not inherited (i.e. not on the prototype chain).
I think it may be normal behaviour here that the key in object
operator is searching through the prototype chain and returning true for Object.prototype.constructor
. See this discussion - it goes over a related topic.
How do I check if an object has a property in JavaScript?
Following MDN documentation, it is not an enumerable field.
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/propertyIsEnumerable
You can perform following test:
var obj = {"t": 23};
obj.propertyIsEnumerable("t")
results: true
obj.propertyIsEnumerable("constructor")
results: false
There is a complete example on this document, under section:
Direct versus inherited properties
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With