JavaScript Basics: Object.prototype.hasOwnProperty
Objects in JavaScript have not only their own properties, but also the properties that are on the objects in their prototype chain. Object.keys
gives a collection of the object's own properties, but the for...in
loop enumerates all properties of the object, including its own properties and its inherited properties.
How can you determine if a particular property is an own property or an inherited property? For this, you can use Object.prototype.hasOwnProperty
. Since this method is available on Object.prototype
, it is accessible to any object that descends from Object.prototype
.
Here is an example:
let myObj = {
name: "Ali",
};
myObj.hasOwnProperty("name"); // true
myObj.hasOwnProperty("toString"); // false
You may have noticed that while this method is on Object.prototype
, most of the other functions for object manipulation are on the Object
constructor itself. This makes it handy, because the method can be called directly on the object, but there is also a problem, and it is the fact that the object may not have descended from Object.prototype
. As I wrote in a previous post, In JavaScript, an object may have no prototype. You can call Object.setPrototypeOf(myObj, null);
. Then, if you call myObj.hasOwnProperty("name")
, you will receive an error:
TypeError: myObj.hasOwnProperty is not a function
For this reason, it is recommended that you call this function like this:
Object.prototype.hasOwnProperty.call(myObj, "name");
Of course, if you know your object's inheritance, you don't need to follow this precaution.
A typical use case for Object.prototype.hasOwnProperty
is in for...in
loops. Since for...in
loops over all the properties of the object, whether own or inherited, sometimes it is necessary to determine whether the property is an own property. Here is an example:
for(let prop in myObj) {
if(myObj.hasOwnProperty(prop)) {
// do something with prop
}
}
Nice educative post.
I agree with you too dear @ghazanfar.ali
good reading
I love your programming short tutorials. It helps us learn some basics in proper way.
I agree with you too dear @zakir.quetta.so 100% love and 100%vote
Thank you dear
very helpful post for programmers. Thank you sir. (Hope you are well. Stay safe.)
Sir you may know that i am new in steemit. so would you please help me to do good and earn a handsome amount ?
چقدر به زبان انسان نزدیکتره جاوا اسکریپت
در سی شارپ ارث بری رو با : نشون میدن
good one. thanks for your great educative post
درود
احسنت بر شما
عالیه
Hi..@ghasemkiani sir ..I need your help..plz sir follow me....I am your ragular upvote and commenter plz sir follow me
Your blogs about JavaScript are really interesting and informative.
thanks for your very informative news...
thats so important...
keep it on
this is very inportant.. and very informative...
i support you definitily...
thanks for sharing....