Have you heard about Hack Frontend Community?Join us on Telegram!
Practice JS Problems

in Operator vs hasOwnProperty() in JavaScript

In JavaScript we have two main ways to check if an object has a specific property:

  1. in — operator that checks everything (including inherited properties).
  2. .hasOwnProperty() — object method that checks only own properties.

Comparison Table

Characteristicin.hasOwnProperty()
Checks including prototypeYesNo, only own properties
Checks only own propertiesNoYes
Can be used with prototypesYesYes
Can throw error on undefined objectYes (if object not checked)Can only be called on object

Usage Example

in — checking including prototypes

const obj = { name: "John" };

console.log("name" in obj);     // true
console.log("toString" in obj); // true (inherited from Object.prototype)

hasOwnProperty() — checking only own properties

console.log(obj.hasOwnProperty("name"));     // true
console.log(obj.hasOwnProperty("toString")); // false (inherited)

Conclusion:

Use hasOwnProperty() when you need to check only the object's own properties. Use in if you also need to check inherited properties from the prototype chain.

Practice JS Problems

By continuing to use the platform, you accept the terms of the Privacy Policy and the use of cookies.