Understanding JavaScript Hasownproperty

Looking to understand how the Javascript hasOwnProperty() works? In this post we explore it in detail, including real examples.

If you have been developing on the web for some time it's likely that you have come across some of the JavaScript built-in objects and methods. One of them is the JavaScript hasOwnProperty() method.

What is it used for?

To put it simply the hasOwnProperty() method is used to determine if an object has the specified property as a direct property of the object you'r testing against. 

To best understand how this method works fully here is an example that you can try out yourself: 

const carObject = {
 make: 'Audi',
 model: 'R8',
 };
 
console.log(carObject.hasOwnProperty('make');
true

console.log(carObject.hasOwnProperty('year'));
false

In the first example we check if the carObject has the property make. The object does meaning that the statement will return true.

In the second we are testing that the object has year which it doesn't resulting in a false outcome.

Other things to know about hasOwnProperty() ?

It will always return a boolean either true or false depending on the outcome.

If the value of the property is null is null or undefined the hasOwnProperty will return true.

The hasOwnProperty will always take in the property name as string or symbol.

Conclusion 

The JavaSctipt hasOwnProperty() is a great way to test if an object has the specified property as a direct property. 

If you found this short post helpful please subscribe to Learnstability for more useful guides and tutorials.

Compare the best online courses.

Search online through Learnstability and discover the top online courses.