Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

hasOwnProperty when iterating over dictionary [duplicate]

I'm pretty new to javascript and I'm trying to iterate over a dictionaries key/values. (And yes, I read a few posts here, but didn't find the answere for.)

So this is my dictionary:

showhidedict = {
    0: ["a"],
    1: [],
    2: ["a", "b"],
    3: []
};

this is my iterating:

for (var value in showhidedict)
    $("#" + showhidedict[value]).hide();

resharper suggests me to add the hasOwnProperty-check into the loop:

if (showhidedict.hasOwnProperty(value))

But why?

the hasOwnProperty-check checks, whether an object has an attribute (here, whether the dictionary contains the key), right? But do I really need the check? Since I iterate over the keys, I know all keys must exist. Are there other points why I should add the check?

like image 355
Matthias Burger Avatar asked Aug 31 '16 06:08

Matthias Burger


2 Answers

If you use the in keyword to iterate, you are iterating object properties, the keys returned are strings, not numbers. In this context of iterating properties, it's prudent to always check you're only iterating that object's own properties, not whatever garbage lies up the prototype chain.

For iterating an Arraylike, the recommended iteration is probably still using a regular for loop with incrementing index. This index will be a number, it will rely on the length property that Arraylikes have. It will not need to check hasOwnProperty.

That being said, I don't think the code you wrote is wrong, but especially in team environments or using external APIs, it's probably prudent to use one of the above two methods. Resharper is all about being prudent with your code.

like image 29
Simon Meskens Avatar answered Oct 15 '22 09:10

Simon Meskens


It is usually recommended to always use hasOwnProperty because indicates whether the object has the specified property on the object itself and avoiding lookup in its prototype chain.

Generally you should never assuming about the environment the code is running on or when your object is created by a different library, or whether the prototype have been extended so hasOwnProperty make your code "safer".

More information on prototype chain.

Reference to Object.prototype.hasOwnProperty().

like image 105
GibboK Avatar answered Oct 15 '22 09:10

GibboK