Sobes.tech
Middle+

What is the difference between the check 'key in result' and 'result.hasOwnProperty(key)'?

sobes.tech AI

Answer from AI

The operator key in result checks whether a property named key exists in the object result or in its prototype chain. That is, it returns true if the property is found anywhere in the object or its prototypes.

The method result.hasOwnProperty(key) only checks the object's own properties, not considering prototypes. It will return true only if the property belongs directly to the object itself, not inherited.

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 prototype
console.log(obj.hasOwnProperty('toString')); // false

Thus, in checks for the presence of a property in the object and its prototypes, while hasOwnProperty checks only in the object itself.

What is the difference between the check 'key in… - sobes.tech