JS: Object.hasOwn β
(new in ECMAScript 2022)
Object.hasOwn(obj, key)-
return true if obj has own property key. Else false.
console.assert( Object.hasOwn({ dog: 1 }, "dog"), );
Object .prototype .hasOwnProperty vs Object.hasOwn
- Object.prototype.hasOwnProperty is older.
- Object.hasOwn is newer. It fixes the problem when object has no parent, or has property
"hasOwnProperty".
/* example of Object.prototype.hasOwnProperty return incorrect result, due to property name collision. Object.hasOwn no have this problem. */ const xx = { "dog": 3, "hasOwnProperty": (x) => false }; // check if xx has property dog console.assert(xx.hasOwnProperty("dog") === false); // check if xx has property dog console.assert(Object.hasOwn(xx, "dog"));