Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

for..in and hasOwnProperty [duplicate]

Tags:

javascript

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]);     } } 
like image 452
scusyxx Avatar asked Oct 04 '12 20:10

scusyxx


People also ask

What is the difference between in and hasOwnProperty?

The key difference is that in will return true for inherited properties, whereas hasOwnProperty() will return false for inherited properties.

What does hasOwnProperty mean?

The hasOwnProperty() method returns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting it).

Is hasOwnProperty necessary?

Then no, you don't need to use the hasOwnProperty() . But the full control over the environment is not something you should count on. It's fine to drop the hasOwnProperty() only until someone somewhere redefines the Object type. Before or even after your script is started.

Can I use hasOwnProperty with an array?

The hasOwnProperty() method returns true if the property is directly present in the object (not in its prototype chain). If an object is an Array, then the hasOwnProperty() method can check if an index is available (not empty) in the array.


1 Answers

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.

like image 78
blockhead Avatar answered Sep 29 '22 13:09

blockhead