JS: Object.hasOwn

By Xah Lee. Date: . Last updated: .

(new in ECMAScript 2022)

Object.hasOwn(obj, prop)

return true if obj has own property prop. Else false.

console.assert(Object.hasOwn({ "p": 1 }, "p"));

Why Object.hasOwn

Object.hasOwn is a better version of Object.prototype.hasOwnProperty. 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 = { "pp": 3, "hasOwnProperty": ((x) => false) };

// check if xx has property pp
console.assert(xx.hasOwnProperty("pp") === false);

// check if xx has property pp
console.assert(Object.hasOwn(xx, "pp") === true);

JavaScript. Access Properties