JS: Object.prototype.hasOwnProperty

JS: Object.prototype.hasOwnProperty

obj.hasOwnProperty(key)

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

// Example of using Object.prototype.hasOwnProperty
const obj = {"p":1};
console.log ( obj.hasOwnProperty ( "p") ); // true
console.log ( obj.hasOwnProperty ( "yyy") ); // false

Example with a symbol key. [see JS: Symbol Tutorial]

// check if a object has own property of a symbol key
const sy = Symbol();
const ob = {};
ob[sy] = 3;
console.log ( ob.hasOwnProperty ( sy ) ); // true

Inherited property doesn't count.

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

const o1 = {"p":1};

// create a object o2, with parent o1
const o2 = Object.create(o1);

console.log ( o2.hasOwnProperty ( "p") ); // false

console.log ( "p" in o1 ); // true
// inherited

[see JS: Access Property]

Reference

ECMAScript 2015 §Abstract Operations#sec-hasownproperty

Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth