Possible Duplicate:
How do I check if an object has a specific property in JavaScript?
I found the following snippet in Twitter’s JavaScript files. Why do they need to call the hasOwnProperty function to see dict has the key property? The for loop is running for each ‘key’ in ‘dict’ which means ‘dict’ has ‘key’. Am I missing a point?
function forEach(dict, f) {
for (key in dict) {
if (dict.hasOwnProperty(key))
f(key, dict[key]);
}
}
Because if you don’t, it will loop through every property on the prototype chain, including ones that you don’t know about (that were possibly added by somebody messing with native object prototypes).
This way you’re guaranteed only the keys that are on that object instance itself.