for own(...) loop (spin-off from Re: for..in, hasOwnProperty(), and inheritance)

Brendan Eich brendan at mozilla.com
Tue Nov 8 14:57:28 PST 2011


On Nov 8, 2011, at 2:16 PM, David Bruant wrote:

> Le 08/11/2011 21:49, Brendan Eich a écrit :
>> 
>> The recommended practice when writing for-in loops in JS today is to write:
>> 
>>   for (i in o) {
>>     if (o.hasOwnProperty(i)) {
>>       body
>>     }
>>   }
> As said in the thread your forked from, this practice is often recommended to not enumerate Object.prototype methods (rather than enumerating only own properties)

Really? That is not its effect of course, and that is not really important in distinction to not enumerating any non-own properties.

Where have you seen this recommended but with the mistaken idea that it filters only Object.prototype enumerable properties? Remember, for over five years extending Object.prototype has been verboten. The really issue is, e.g., PrototypeJS extending Array.prototype (not that there's anything wrong with that!).


>> Although many JS developers do not follow the recommendation (out of ignorance or intentionally, doesn't matter).
>> 
>> Should ES.next provide sugar for the recommended pattern? To make it compose with declarations and destructuring in the for head, it should use a contextual keyword immediately after 'for':
>> 
>>   for own (i in o) {
>>     body
>>   }
>> 
>> This is a small thing but it might pay off in the long run.
> Why would developers use for own while they currently do not use hasOwnProperty?

Several reasons come to mind:

* shorter and easier to type.
* faster by definition.
* I know CoffeeScript, I'm writing raw JS for a new gig that requires it.


> I really am skeptical on this.
> Enumeration of own enumerable properties can be done with Object.keys. Why not encourage people to use this?

Because

1. It eagerly reifies an array of keys, which can hurt for high-call-frequency and/or large-object.
2. You have to wrap //body// in function(){...}, which introduces wrong-this and other TCP (break/return/continue/arguments) hazards. These are real, they bite programmers too often.

/be


> Are you also proposing an addition of for own (... of ...) if for-own-in and for-of are both accepted?
> 
> David

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20111108/033cb66f/attachment.html>


More information about the es-discuss mailing list