Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save cihat/08258ab7c3b6518c7e073b0427a2d7da to your computer and use it in GitHub Desktop.

Select an option

Save cihat/08258ab7c3b6518c7e073b0427a2d7da to your computer and use it in GitHub Desktop.
In most cases, the in operator is the best way to determine whether
the property exists in an object. It has the added benefit of not evaluating the value of the property, which can be important if such an evaluation is likely to cause a performance issue or an error.
In some cases, however, you might want to check for the existence of
a property only if it is an own property. The in operator checks for both
own properties and prototype properties, so you’ll need to take a different
approach. Enter the hasOwnProperty() method, which is present on all objects
and returns true only if the given property exists and is an own property.
For example, the following code compares the results of using in versus
hasOwnProperty() on different properties in person1:
var person1 = {
name: "Nicholas",
sayName: function() {
console.log(this.name);
}
};
console.log("name" in person1); // true
console.log(person1.hasOwnProperty("name")); // true
console.log("toString" in person1); // true
console.log(person1.hasOwnProperty("toString")); // false
In this example, name is an own property of person1, so both the in
operator and hasOwnProperty() return true. The toString() method, however, is a prototype property that is present on all objects. The in operator returns true for toString(), but hasOwnProperty() returns false u. This
is an important distinction that is discussed further in Chapter 4.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment