tc39/proposal-negated-in-instanceof

Is it really necessary to have a not in?

Closed this issue · 2 comments

I don't see the need for a !key in obj, in javascript there has been Object.hasOwn for a long time, this method is the most recommended to check if an object has a property.

const foo = { bar: "Foo Bar" };

if (Object.hasOwn(foo, "bar")) {
  console.log("foo has a bar property");
} else {
  console.log("foo doesn't have the bar property");
}

The use of in is completely discouraged in the JS communities I frequent.

ljharb commented

hasOwn is different than in, and there's no reason in should be discouraged when you're checking "will a Get() of the property produce something".

A negated in is as necessary as a negated instanceof - both of these negated operators solve the same error-proneness, inconsistency, readability and developer experience issues, as per the README.

As @ljharb points out above, nobody should be discouraged from using in instead of Object.hasOwn whenever they don't care if they are checking against the object's own or inherited properties. In practice, it turns out this is often the case - Sourcegraph data shows that in expressions are much more popular than Object.hasOwn, or even Object.hasOwnProperty.

Overall, the fact that Object.hasOwn exists doesn't really solve any of the problems associated with negated in and negated instanceof expressions.