Blog logo on a black background with the words "Discover What's Next in Tech!"

It's #FrontendFriday - JavaScript Insights: hasOwnProperty vs. hasOwnProperty.call

,

Hello #FrontendFriday-reader,

You've always wondered how the Object.prototype.hasOwnProperty Method Zero can be made safer. Then the following article is just right for you.

 

In the JavaScript universe, there are several ways of checking the existence of a property within an object. A common one is the use of the hasOwnPropterty method. The following image shows an example of its use. As we can see, the normal variant also works for null properties.

 

 

The syntax in the example above is very simple. Define an object and call the method with the property to be checked. But have you ever asked why, for example, Webpack calls the hasOwnProperty.call variant when bundling. The reason for this is very simple: the common hasOwnPropterty Method is not zero safe! Here is the proof:

 

 

In JavaScript, you can also use an object without prototypical inheritance. In this case, an error is thrown in the console. Which is very unpleasant! By using hasOwnProperty.call the problem would disappear into thin air. Let's take a look at the whole thing in another example.

 

 

We no longer see any error. Yes, it's an absolutely marginal case. But why not take advantage of the additional security from the outset?

 

The Webfrontend FG wishes you a wonderful weekend, may the code be with you.

 

Learn more about frontend development

 

Dennis Stricker

About ME

Stricker Dennis works as a passionate developer at the company doubleSlash in Friedrichshafen on Lake Constance. He completed his Master of Science degree at the Ravensburg-Weingarten University of Applied Sciences. His areas of specialization include the development and conception of modern Web applications and mobile apps in the B2B environment.

All contributions from Dennis Stricker

Learn more

Further information on our website and in our newsletter

Arrow up