`for in` and prototypes

The problem

Sometimes, I see code like:

or

I had a bad feeling about this until I got bitten by it recently. Consider the following code:

#Best practices So for in is convenient but one have to remember that it also iterates over the prototype of the object. If you want to iterate over a string, prefer something like:

For an array, you can even use forEach

So when should you use for in? When you want to iterate over the keys of an objects. The following two ways are corrects:

lodash has also a method to achieve the same effect: _.forOwn.

So remember that for in will goes through the prototypes of your object as well. Since extending the prototype of built-in objects is questionable (but it's a bit religious here), and some libraries do that, prefer robust code.