Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will hasOwnProperty ever return false from inside a for...in loop?

Tags:

javascript

If I do this:

for (var i in obj) {
    if (obj.hasOwnProperty(i)) console.log("Has property: " + i);
    else console.log("Doesn't have property: " + i);
}

Will obj.hasOwnProperty(i) ever return false? If so, when?

like image 854
Juan Avatar asked Aug 17 '12 16:08

Juan


2 Answers

The idea of using hasOwnProperty within a loop is to resolve to false when looping over inherited properties. This avoids what Douglas Crockford refers to as a "deep-dredge."

Example from https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/hasOwnProperty :

var buz = {
  fog: 'stack'
};

for (var name in buz) {
  if (buz.hasOwnProperty(name)) {
    alert("this is fog (" + name + ") for sure. Value: " + buz[name]);
  }
  else {
    alert(name); // toString or something else
  }
}
like image 162
Matthew Blancarte Avatar answered Sep 27 '22 19:09

Matthew Blancarte


Example from https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/hasOwnProperty - doesn't show when hasOwnProperty can return false.

Here's a test case that does show that:

// From some library or earlier in your code
Object.prototype.xxx = "xxx";

// Your object
var data = { member: "member" };

for (var key in data) {
    if( data.hasOwnProperty(key) ) {
        alert(key); // alert("member")
    }
    else {
        alert(key); // alert("xxx")
    }
}
like image 31
Ilia Barahovsky Avatar answered Sep 27 '22 17:09

Ilia Barahovsky