1var person = {
2 "first_name": "Bob",
3 "last_name": "Dylan"
4};
5person.hasOwnProperty('first_name'); //returns true
6person.hasOwnProperty('age'); //returns false
1if (someVar.hasOwnProperty('someProperty') ) {
2 // do something();
3} else {
4 // do somethingElse();
5}
1var person = {'first_name': 'bill','age':20};
2
3if ( person.hasOwnProperty('first_name') ) {
4 //person has a first_name property
5}
6
1// JavaScript does not protect hasOwnProperty method
2var foo = {
3 // overriding foo's default hasOwnProperty method
4 hasOwnProperty: function() {
5 return false;
6 },
7 bar: 'data'
8};
9foo.hasOwnProperty('bar'); // false always
10
11// Hence, to prevent this, use Object.prototype.hasOwnProperty as follows-
12Object.prototype.hasOwnProperty.call(foo, 'bar'); // true
1The hasOwnProperty() method returns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting it).
2
3const object1 = {};
4object1.property1 = 42;
5
6console.log(object1.hasOwnProperty('property1'));
7// expected output: true
8
9console.log(object1.hasOwnProperty('toString'));
10// expected output: false
11
1//
2//2021 - Object.hasOwn as a replacement for Object.hasOwnProperty()
3
4//As other answers indicated, hasOwnProperty will check for an object own properties in contrast to in which will also check for inherited properties.
5
6//There is a new alternative method called Object.hasOwn() and is intended to be a replacement for Object.hasOwnProperty()**
7
8const person = { name: 'dan' };
9
10console.log(Object.hasOwn(person, 'name'));// true
11console.log(Object.hasOwn(person, 'age'));// false
12
13const person2 = Object.create({gender: 'male'});
14
15console.log(Object.hasOwn(person2, 'gender'));// false
16 Run code snippet