Sobes.tech
Middle

What is the difference between the 'in' operator and the 'hasOwnProperty' method?

sobes.tech AI

Answer from AI

The in operator and the hasOwnProperty method in JavaScript are used to check for the presence of a property in an object, but they work differently:

  • in checks whether a property with the specified name exists in the object or in its prototype chain.

  • hasOwnProperty checks whether a property exists directly on the object itself, without considering prototypes.

Example:

const obj = { a: 1 };
console.log('a' in obj); // true
console.log(obj.hasOwnProperty('a')); // true

console.log('toString' in obj); // true, because toString is in the Object prototype
console.log(obj.hasOwnProperty('toString')); // false

Thus, if you need to check whether a property belongs directly to the object itself and is not inherited, use hasOwnProperty. If it's enough to check for the presence of a property anywhere in the chain, use in.

What is the difference between the 'in' operator and… - sobes.tech