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.log(xx.hasOwnProperty("p"));
console.log(xx.hasOwnProperty("y") === false);

Function spec verification

Work with symbol key

// Object.prototype.hasOwnProperty works on symbol key
const ss = Symbol();
const xx = {};
xx[ss] = 3;
console.log(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.log(xson.car === 1);

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

JavaScript. Access Properties