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");
}
};
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.