Loading...
Loading...
By continuing to use the platform, you accept the terms of the Privacy Policy and the use of cookies.
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.| 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 |
const obj = { name: "John" };
console.log("name" in obj); // true
console.log("toString" in obj); // true (inherited from Object.prototype)
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.