What's the difference between the in operator and the hasOwnProperty method in objects?
As you know both of these features check if a property exists in an object. It will return true
false. The difference between them is that the in
operator also checks the objects' Prototype Chain if the property was not found in the current object while the hasOwnProperty
method just checks if the property exists in the current object ignoring the Prototype Chain.
// We'll still use the object in the previous question.
console.log("prop" in o); // This logs true;
console.log("toString" in o); // This logs true, the toString method is available in this object's prototype which is the Object.prototype
console.log(o.hasOwnProperty("prop")); // This logs true
console.log(o.hasOwnProperty("toString")); // This logs false, does not