Owned or inherited? Four ways to ask about your own object and key: which can be fooled, and by what? An interactive Object.hasOwn playground: change the…
Checking property ownership is everywhere: JSON data, config, looping over objects. The old ways give subtle bugs: prototype-less objects from a library, a field named "hasOwnProperty", a legitimate 0 or undefined. Object.hasOwn removes that whole class of bugs.
The three old ways have traps; Object.hasOwn has none
o.hasOwnProperty(k) throws a TypeError The object was made with Object.create(null) and has no inherited methods. Use Object.hasOwn(o, k) (or, for old browsers, Object.prototype.hasOwnProperty.call(o, k)).'toString' in o is true though it was never written in also walks the prototype chain. For "own only", use Object.hasOwn; use in only when inherited keys should count.if (o[k]) says missing though the key is there That checks for a truthy value, not existence. A legitimate 0, '', false or undefined reads as missing. Use Object.hasOwn.o.hasOwnProperty breaks There is no inherited method to call, so TypeError. Object.hasOwn still answers.in says is there and hasOwn says is not toString, valueOf, constructor: all inherited from Object.prototype.0 or undefined The key is there, but o[k] is falsy. Checking existence is not checking the value.