Skip to main content
Practice Problems

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:

  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

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 ready
Premium

A concise answer to help you respond confidently on this topic during an interview.

Finished reading?
Practice Problems