Difference between in operator and hasOwnProperty() method in JavaScript
In JavaScript we have two main ways to check if an object has a specific property:
in— operator that checks everything (including inherited properties)..hasOwnProperty()— object method that checks only own properties.
Comparison Table
| Characteristic | in | .hasOwnProperty() |
|---|---|---|
| Checks including prototype | Yes | No, only own properties |
| Checks only own properties | No | Yes |
| Can be used with prototypes | Yes | Yes |
Can throw error on undefined object | Yes (if object not checked) | Can only be called on object |
Usage Example
in — checking including prototypes
javascript
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
javascript
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.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.