Skip to content

Using `hasOwnProperty` Safely in JavaScript

  • javaScript
  • quick tip

In JavaScript, the hasOwnProperty method is used to check if a property exists on an object and if it is directly attached to that object, as opposed to being inherited from its prototype.

However, using hasOwnProperty can sometimes lead to unexpected behavior, especially when dealing with objects that don't inherit from the Object prototype. For example, consider the following code:

let obj = Object.create(null);
console.log(obj.hasOwnProperty); // undefined

Here, obj is an object that does not inherit from the Object prototype, and as a result, it does not have a hasOwnProperty method. Attempting to use hasOwnProperty on obj would result in a TypeError.

This is where Object.prototype.hasOwnProperty.call comes in as a safer alternative. By using call, you can bind the hasOwnProperty method to a specific object, allowing you to check if a property exists on that object even if it doesn't have a hasOwnProperty method.

Here's an example of how you can use Object.prototype.hasOwnProperty.call:

let obj = Object.create(null);
console.log(Object.prototype.hasOwnProperty.call(obj, 'propertyName')); // false

In this example, Object.prototype.hasOwnProperty.call is used to check if the property propertyName exists on obj. Since obj does not have a propertyName property, the result is false.

It's important to note that Object.prototype.hasOwnProperty.call only works with objects that have a null or undefined prototype. If the object has a prototype other than null or undefined, you can use hasOwnProperty directly without any issues.

Conclusion

In conclusion, using Object.prototype.hasOwnProperty.call is a safer alternative to hasOwnProperty because it allows you to check if a property exists on an object, even if the object does not have a hasOwnProperty method. This can help you avoid potential issues with inheritance and ensure your code works as expected.