In this article, we will look at hasOwnProperty() method in javascript, its purpose and use it to check if an object has an entry with given key along with example programs

Javascript object
A javascript object is a collection of key-value pairs enclosed between curly braces. A single key-value pair is separated by a colon(:) while multiple key-value pairs are separated by a comma(,).
Below is an example of an object in javascript.

let laptop = {
  brand: 'Apple', 
  model: 'Macbook Air',
  ram: 8GB
}

To know more about javascript object, read this article.
Object.hasOwnProperty()
Many times you need to check if a property exists in an object so that you can get its value and use it somewhere.
All javascript objects contain hasOwnProperty() method which accepts a property name as a string argument and returns true if the property belongs to the object and false if it does not.
Example,

let laptop = {
  brand: 'Apple', 
  model: 'Macbook Air',
  ram: '8GB'
}
// check if object has property
const isBrandName = laptop.hasOwnProperty('brand');
document.write('Has brand: ' + isBrandName);
// access property
if(isBrandName) {
 document.write('Laptop brand: '+ laptop['brand']);
}

This prints

Has brand: true
Laptop brand: Apple

Before accessing a property, it is always better to check if it even exists in the object or not and this can be done using hasOwnProperty().

Remember that hasOwnProperty() only checks for the existence of a property only in the object on which it is invoked.
It does not check the property in the object’s prototype or parent tree.

hasOwnProperty() vs in
There is another way to check if a property exists in an object or not with in operator.
So the above code can be written using in operator as

let laptop = {
  brand: 'Apple', 
  model: 'Macbook Air',
  ram: '8GB'
}
// check if object has property
if('brand' in laptop) {
 document.write('Laptop brand: '+ laptop['brand']);
}

However, there is a slight difference between hasOwnProperty() and in.

hasOwnProperty() does not check for the property existence in an object’s parent tree while in goes up the object tree to find the property if it cannot find it in the current object.

So, if you want to check if a property exists in only the current object, then use hasOwnProperty() and if you also want to inspect an object’s parent, then use in.

Hope this article was useful for you to understand the meaning of hasOwnProperty() method in javascript.

0
Close Menu

Never Miss an article !

Get the new post delivered straight into your inbox, enter your email and hit the button

You have successfully subscribed to the newsletter

There was an error while trying to send your request. Please try again.

codippa will use the information you provide on this form to be in touch with you and to provide updates and marketing.