What is property in hasOwnProperty in JavaScript?
Here is a short and precise answer:
In JavaScript, every object has a bunch of built-in key-value pairs that have meta information about the object. When you loop through all the key-value pairs using for...in
construct/loop for an object you're looping through this meta-information key-value pairs too (which you definitely don't want).
Using hasOwnPropery(property)
filters-out these unnecessary looping through meta information and directly checks that is the parameter property
is a user-given property in the object or not.
By filters-out, I mean, that hasOwnProperty(property)
does not look if, property
exists in Object's prototype chain aka meta information.
It returns boolean true/false
based on that.
Here is an example:
var fruitObject = {"name": "Apple", "shape": "round", "taste": "sweet"};
console.log(fruitObject.hasOwnProperty("name")); //true
console.log(Object.prototype.hasOwnProperty("toString");) //true because in above snapshot you can see, that there is a function toString in meta-information
I hope it's clear!
hasOwnProperty
returns a boolean value indicating whether the object on which you are calling it has a property with the name of the argument. For example:
var x = {
y: 10
};
console.log(x.hasOwnProperty("y")); //true
console.log(x.hasOwnProperty("z")); //false
However, it does not look at the prototype chain of the object.
It's useful to use it when you enumerate the properties of an object with the for...in
construct.
If you want to see the full details, the ES5 specification is, as always, a good place to look.