0

The code I'm referencing comes from this answer:

Array.prototype.getUnique = function(){
   var u = {}, a = [];
   for(var i = 0, l = this.length; i < l; ++i){
      if(u.hasOwnProperty(this[i])) {
         continue;
      }
      a.push(this[i]);
      u[this[i]] = 1;
   }
   return a;
}

What is the purpose of hasOwnProperty here? I've ran a version of the method that does not use it and it works just the same:

Array.prototype.getUnique = function(){
   var u = {}, a = [];
   for(var i = 0, l = this.length; i < l; ++i){
      if(u[this[i]] !== undefined) {
         continue;
      }
      a.push(this[i]);
      u[this[i]] = 1;
   }
   return a;
}
Community
  • 1
  • 1
Levi Hackwith
  • 9,232
  • 18
  • 64
  • 115

2 Answers2

4

The .hasOwnProperty() test allows the code to exclude properties inherited from the prototype chain.

In your example code, if the array contained the string "toString", then your revised code would be fooled into thinking that it had already seen that value — all objects inherit the "toString" function from the Object prototype.

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • The code you posted uses an object to keep track of values it's seen so far in an array. It doesn't seem to care whether or not the values are numbers, though you're correct that if all the values in arrays for which the code is used are numbers then the test makes no difference. And you never know whether somebody might put a property called "12" on the Object prototype :-) – Pointy May 29 '13 at 18:56
3

What if an object has a property, and that property has the value undefined or has an ancestor object with that property?

That's the main difference.

For example:

var a = {b:undefined};
a.b !== undefined; //false
a.hasOwnProperty("b");//true

Not having something, and having that something yourself with the value undefined are two different things.

hasOwnProperty(name) checks if the object has a property named 'name' declared directly on it.

obj.propertyName === undefined - checks if somewhere along the prototype chain (in the object, or in its prototype, and so on) , the object has a property with name 'propertyName' and its value is undefined, or the object and its chain have no such property.

Here are some examples illustrating the differences between the two:

var a={b:undefined};
a.hasOwnProperty(b);//true
a.b!==undefined;//false

//Create a new object, with b being the prototype
var c = Object.create(b);
c.hasOwnProperty("b");//false
c.b;//undefined;
b in c;// true
c.b!==undefined;//false
Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
  • 1
    Downvoter care to explain why? OP asked about the difference between an undefined check and hasOwnProperty, not the difference betwee hasOwnProperty and the `in` operator. – Benjamin Gruenbaum May 29 '13 at 18:05