If (Key in Object) or If(Object.Hasownproperty(Key)

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:

  1. 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?
  2. You're assigning to Teacher.prototype.greeting, then later replacing Teacher.prototype entirely (Teacher.prototype = Object.create(Person.prototype);). So you won't have the greeting method on it.

  3. If you replace the object on Teacher.prototype the way you are, it's important to make sure its constructor property is correct:

    Teacher.prototype = Object.create(Person.prototype);
    Teacher.prototype.constructor = Teacher; // <===

But: Since you're using ES2015+ features anyway (arrow functions, template literals, ...), you can make this all much simpler by using class syntax.

How do I check if an object has a specific property in JavaScript?

2022 UPDATE

Object.hasOwn()

Object.hasOwn() is recommended over Object.hasOwnProperty() because it works for objects created using Object.create(null) and with objects that have overridden the inherited hasOwnProperty() method. While it is possible to workaround these problems by calling Object.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:

The hasOwnProperty() method returns a boolean indicating whether the
object has the specified property as own (not inherited) property.

The 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 ones
  • for in + hasOwnProperty additionally tests all looked up properties for whether they are own properties.

Even if there are no inherited enumerable properties, it is still more work to do than not.

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



Leave a reply



Submit