Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Benefit of using Object.hasOwnProperty vs. testing if a property is undefined

Tags:

Since hasOwnProperty has some caveats and quirks (window / extensive use in Internet Explorer 8 issues, etc.):

Is there any reason to even use it? If simply testing if a property is undefined, is it better justified and more simplistic?

For example:

var obj = { a : 'here' };  if (obj.hasOwnProperty('a')) { /* do something */ }  if (obj.a !== undefined) { /* do something */ } // Or maybe (typeof (obj.a) !== 'undefined') 

I'd prefer to be using the most cross-browser friendly, and up to date methodology.

I've also seen this prototype overwritten for hasOwnProperty, which works, but I'm not sold on its usefulness...

if (!Object.prototype.hasOwnProperty) {     Object.prototype.hasOwnProperty = function(prop) {         var proto = this.__proto__ || this.constructor.prototype;         return (prop in this) && (!(prop in proto) || proto[prop] !== this[prop]);     }; } 
like image 883
Mark Pieszak - Trilon.io Avatar asked Jun 17 '13 14:06

Mark Pieszak - Trilon.io


People also ask

Is hasOwnProperty necessary?

Then no, you don't need to use the hasOwnProperty() . But the full control over the environment is not something you should count on. It's fine to drop the hasOwnProperty() only until someone somewhere redefines the Object type. Before or even after your script is started.

What does hasOwnProperty method do?

The hasOwnProperty() method returns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting it).

What is the difference between in and hasOwnProperty?

The key difference is that in will return true for inherited properties, whereas hasOwnProperty() will return false for inherited properties.

Is hasOwnProperty case sensitive?

Yes, it's case sensitive, because JavaScript is case sensitive.


2 Answers

hasOwnProperty does not check for undefined values. It only checks if a property is assigned to the object even if is undefined:

var obj = { a : undefined }; obj.hasOwnProperty("a") // true obj.a === undefined     // true obj.hasOwnProperty("b") // false obj.b === undefined     // true 
like image 64
dpineda Avatar answered Sep 21 '22 07:09

dpineda


The hasOwnProperty method checks that a property is assigned to the object directly.

So, if property 'a' is in the prototype, hasOwnProperty will filter that.

function NewClass() {} NewClass.prototype = { a: 'there' }; var obj = new NewClass();  if (obj.hasOwnProperty('a')) { /* Code does not work */ } if (obj.a !== undefined) { /* Code works */ } 

So, hasOwnProperty is safer in many cases.

like image 27
Pavel Gruba Avatar answered Sep 19 '22 07:09

Pavel Gruba