Question

I have created a for in loop and am trying to understand why when I run it, the console logs 2x "We got it." It seems like if I was looping through you would only want it to log once if it found the property once.

Also im a JS newbie so if you have any feedback on my formatting that is always appreciated. Happy Holidays!

var obj = {
  company: 'planters',
  peanuts: 'plain'
};

for (var key in obj) {
  if (obj.hasOwnProperty('peanuts')) {
    console.log('We got it');
  } else {
    console.log("We cant find it");
  }
};
Was it helpful?

Solution

The reason that is happening is you are looping it for 2 iterations (which is the length of the object) and looking if object has property peanuts, which is true in both the cases.

OTHER TIPS

The for loop is unnecessary. You're not using key. It's just equivalent to running the body of the for loop the number of times of keys there are in the object (and parents).

Try

for (var key in obj) {
  if (obj.hasOwnProperty(key)) {  // you mean this
    console.log('We got ', key);
  } else {
    console.log("We cant find it");
  }
};

to see what's going on here better.

If you're looking for a specific key, you have to compare it with key.

var found = false;
for (var key in obj) {
    if (obj.hasOwnProperty(key) && key == 'peanuts') {
        console.log('We got it');
        found = true;
        break;
    }
}
if (!found) {
    console.log("We can't find it");
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top