Skip to content

Instantly share code, notes, and snippets.

@cihat
Created November 16, 2020 10:55
Show Gist options
  • Save cihat/dc6b5a076015d05c0d8060bad8a06db3 to your computer and use it in GitHub Desktop.
Save cihat/dc6b5a076015d05c0d8060bad8a06db3 to your computer and use it in GitHub Desktop.
Detecting Properties
Because properties can be added at any time, it’s sometimes necessary to
check whether a property exists in the object. New JavaScript developers
often incorrectly use patterns like the following to detect whether a property exists:
// unreliable
if (person1.age) {
// do something with age
}
The problem with this pattern is how JavaScript’s type coercion affects
the outcome. The if condition evaluates to true if the value is truthy (an
object, a nonempty string, a nonzero number, or true) and evaluates to
false if the value is falsy (null, undefined, 0, false, NaN, or an empty string).
Because an object property can contain one of these falsy values, the
example code can yield false negatives. For instance, if person1.age is 0,
then the if condition will not be met even though the property exists.
A more reliable way to test for the existence of a property is with the in
operator.
The in operator looks for a property with a given name in a specific
object and returns true if it finds it. In effect, the in operator checks to see
if the given key exists in the hash table. For example, here’s what happens
when in is used to check for some properties in the person1 object:
console.log("name" in person1); // true
console.log("age" in person1); // true
console.log("title" in person1); // false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment