Difference between Object.keys() and Object.hasOwnProperty()?
Actually Object.keys({ a: 1 })
will return [ 'a' ]
which is an Array containing the object's keys. This statement will return false
:
console.log('a' in ['a']); // false
So you could use : console.log(Object.keys({ a: 1 }).includes('a')); // true
But it's more straight forward to simply use :console.log({ a: 1 }.hasOwnProperty('a')); // true
hasOwnProperty & Object.keys in javascript not working as expected
The name
, age
, etc., properties on teacher1
are own properties. They are not inherited from teacher1
's prototype (Teacher.prototype
) or its prototype (Person.prototype
). Although it's Person
that assigns them, they're still own properties. this
in the call to Person
from Teacher
is the object that will be assigned to teacher1
, so
this.age = age;
...makes age
an own property of teacher1
.Once the property has been created on the object, there's no way to know what function (if any) created it.
There are a couple of other problems with your code:
You're assigning an arrow function to
Teacher.prototype.greeting
. Don't use arrow functions for methods that will be inherited,this
won't be set correctly. A couple of related questions whose answers may be useful:- Methods in ES6 objects: using arrow functions
- What's the meaning of “=>” (an arrow formed from equals & greater than) in JavaScript?
You're assigning to
Teacher.prototype.greeting
, then later replacingTeacher.prototype
entirely (Teacher.prototype = Object.create(Person.prototype);
). So you won't have thegreeting
method on it.If you replace the object on
Teacher.prototype
the way you are, it's important to make sure itsconstructor
property is correct:Teacher.prototype = Object.create(Person.prototype);
Teacher.prototype.constructor = Teacher; // <===
class
syntax. How do I check if an object has a specific property in JavaScript?
2022 UPDATE
Object.hasOwn()
Object.hasOwn()
is recommended overObject.hasOwnProperty()
because it works for objects created usingObject.create(null)
and with objects that have overridden the inheritedhasOwnProperty()
method. While it is possible to workaround these problems by callingObject.prototype.hasOwnProperty()
on an external object,Object.hasOwn()
is more intuitive.
Example
const object1 = {
prop: 'exists'
};
console.log(Object.hasOwn(object1, 'prop'));
// expected output: true
Original answer
I'm really confused by the answers that have been given - most of them are just outright incorrect. Of course you can have object properties that have undefined, null, or false values. So simply reducing the property check to typeof this[property]
or, even worse, x.key
will give you completely misleading results.
It depends on what you're looking for. If you want to know if an object physically contains a property (and it is not coming from somewhere up on the prototype chain) then object.hasOwnProperty
is the way to go. All modern browsers support it. (It was missing in older versions of Safari - 2.0.1 and older - but those versions of the browser are rarely used any more.)
If what you're looking for is if an object has a property on it that is iterable (when you iterate over the properties of the object, it will appear) then doing: prop in object
will give you your desired effect.
Since using hasOwnProperty
is probably what you want, and considering that you may want a fallback method, I present to you the following solution:
var obj = {
a: undefined,
b: null,
c: false
};
// a, b, c all found
for ( var prop in obj ) {
document.writeln( "Object1: " + prop );
}
function Class(){
this.a = undefined;
this.b = null;
this.c = false;
}
Class.prototype = {
a: undefined,
b: true,
c: true,
d: true,
e: true
};
var obj2 = new Class();
// a, b, c, d, e found
for ( var prop in obj2 ) {
document.writeln( "Object2: " + prop );
}
function hasOwnProperty(obj, prop) {
var proto = obj.__proto__ || obj.constructor.prototype;
return (prop in obj) &&
(!(prop in proto) || proto[prop] !== obj[prop]);
}
if ( Object.prototype.hasOwnProperty ) {
var hasOwnProperty = function(obj, prop) {
return obj.hasOwnProperty(prop);
}
}
// a, b, c found in modern browsers
// b, c found in Safari 2.0.1 and older
for ( var prop in obj2 ) {
if ( hasOwnProperty(obj2, prop) ) {
document.writeln( "Object2 w/ hasOwn: " + prop );
}
}
The above is a working, cross-browser, solution to hasOwnProperty()
, with one caveat: It is unable to distinguish between cases where an identical property is on the prototype and on the instance - it just assumes that it's coming from the prototype. You could shift it to be more lenient or strict, based upon your situation, but at the very least this should be more helpful. Is there a benefit to use hasOwnProperty() when iterating through object keys in JavaScript
The docs indicate that:
TheThe hasOwnProperty() method returns a boolean indicating whether the
object has the specified property as own (not inherited) property.
hasOwnProperty
method ensure that the property you are checking is directly on an instance of an object but not inherited from its prototype chain. If you don't check, it will loop through every property on the prototype chain.const obj = {
prop1: [],
prop2: {},
prop3: "",
prop4: 0,
prop5: null,
prop6: undefined
}
obj.prototype = {foo: 'bar'};
P/s: NOTE that:
JavaScript does not protect the property name hasOwnProperty
; thus, if the possibility exists that an object might have a property with this name, it is necessary to use an external hasOwnProperty
to get correct results:
var foo = {
hasOwnProperty: function() {
return false;
},
bar: 'Here be dragons'
};
foo.hasOwnProperty('bar'); // always returns false
So you need to use:Object.prototype.hasOwnProperty.call(foo, 'bar');
How do I check if an object has a key in JavaScript?
Try the JavaScript in operator.
if ('key' in myObj)
And the inverse.if (!('key' in myObj))
Be careful! The in
operator matches all object keys, including those in the object's prototype chain.Use myObj.hasOwnProperty('key')
to check an object's own keys and will only return true
if key
is available on myObj
directly:
myObj.hasOwnProperty('key')
Unless you have a specific reason to use the in
operator, using myObj.hasOwnProperty('key')
produces the result most code is looking for. Why is Object.keys faster than hasOwnProperty?
Object.keys
looks up all own, enumerable properties (oh, and arrays are fast).for in
additionally looks up inherited enumerable properties, not only own onesfor in
+hasOwnProperty
additionally tests all looked up properties for whether they are own properties.
Practical differences of Object.hasOwnProperty vs Object.prototype.hasOwnProperty
Using Object.hasOwnProperty
is weird because it makes it seem like you are using a static method like Object.assign()
.
It still works because if a property is not found on Object
, it falls back to Function.prototype
object. And, this object inherits from Object.prototype
. So, if you have a custom implementation for Function.prototype.hasOwnProperty
, then Object.hasOwnProperty
will use that implementation instead of Object.prototype.hasOwnProperty
console.log( Object.hasOwnProperty === Object.prototype.hasOwnProperty ) // trueconsole.log( Object.getPrototypeOf(Object) === Function.prototype ) // trueconsole.log( Object.getPrototypeOf(Function.prototype) === Object.prototype ) // true
Function.prototype.hasOwnProperty = _ => 'custom implementaion in Function.prototype'
const obj = { prop: 10 }
console.log(Object.hasOwnProperty.call(obj, 'prop')) // custom implementaionconsole.log(Object.prototype.hasOwnProperty.call(obj, 'prop')) // true
Javascript object.hasOwnProperty() vs Reflect.has()
One major difference is that Reflect.has
will check whether any of the object's internal prototypes have the key, whereas hasOwnProperty
only checks whether the object itself has the key:
const proto = { foo: 'foo' };const obj = Object.create(proto);console.log(Reflect.has(obj, 'foo'));console.log(obj.hasOwnProperty('foo'));
Related Topics
Javascript: Dynamically Creating Variables for Loops
Check If Array Contains All Elements of Another Array
How to Find Out with Jquery If an Element Is Being Animated
Understanding JavaScript Promises; Stacks and Chaining
Why Does JavaScript's Regex.Exec() Not Always Return the Same Value
Check If Year Is Leap Year in JavaScript
Objects Are Not Valid as a React Child (Found: [Object Promise])
How to Pull the File Name from a Url Using JavaScript/Jquery
How to Access Object Using Dynamic Key
Conversion Between Utf-8 Arraybuffer and String
How to Change the Pop-Up Position of the Jquery Datepicker Control
$(Document).Ready(Function() VS $(Function(){
Onclick Event Binding in React.Js
What's the API Key for in Google Maps API V3
How to Set Node_Env to Production/Development in Os X
How to Send the "&" (Ampersand) Character via Ajax
Use of @ Symbol in Node Module Names
Counting Frequency of Characters in a String Using JavaScript