JS: Object.prototype.hasOwnProperty ❌

By Xah Lee. Date: . Last updated: .
obj.hasOwnProperty(key)

Return true if object obj has own property key key (string or Symbol). Else, false.

🟢 TIP: better is Object.hasOwn.

const xx = { "p": 1 };
console.assert(xx.hasOwnProperty("p"));
console.assert(xx.hasOwnProperty("y") === false);

Function spec verification

Work with symbol key

// Object.prototype.hasOwnProperty works on symbol key
const ss = Symbol();
const xx = { [ss]: 3 };
console.assert(xx.hasOwnProperty(ss) === true);

Parent Property return false

// Object.prototype.hasOwnProperty return false if the property is not own property

const xdad = { "car": 1 };
const xson = { "toy": 1 };
Reflect.setPrototypeOf(xson, xdad);

// xson has property car, via inheritance
console.assert(xson.car === 1);

// not its own
console.assert(xson.hasOwnProperty("car") === false);

JavaScript. Access Properties