In Javascript to find all the values in a hash I have seen the following code:
var myHash = {};
myHash['one'] = 1;
myHash['two'] = 2;
for (var key in myHash) {
if (myHash.hasOwnProperty(key)) {
//do something
}
}
What is the point of having the hasOwnProperty check here?
The point is to make sure that
keyis a property defined directly onmyHashand not one that was inherited through a prototype chain. Usingindoesn’t automatically filter out inherited properties, so you get to do it yourself.But, as others have said, it isn’t necessary for your particular example.
Source:
hasOwnPropertyon MDN.