<offtopic>

On Mon, Mar 19, 2012 at 9:35 AM, Daniel Friesen
<li...@nadir-seen-fire.com>wrote:

> On Mon, 19 Mar 2012 00:40:54 -0700, Dmitriy Sintsov <ques...@rambler.ru>
> wrote:
> var jqgmap = [];
>
>> for ( var mapIndex in jqgmap ) {
>>
>
> This is VERY bad JavaScript coding practice. Please use $.each().
>

This is rather exaggerated. Even more when looking at that suggestion.

Arrays should, indeed, not be enumerated with a for-in loop. Arrays in JS
can only contain numeral indices, so they should simply be iterated with a
simple for-loop like this `for (i = 0; i < myArr.length; i += 1) { .. }`
(maybe cache length for slight performance gain by reducing property
lookups).

Using $.each has overhead (+1+n function invocations). When given an array
it will do a simple for-loop with a counter. It has overhead of 1+n
additional function invocations and context creations. In most cases there
is no use for it. There is one case where it is handy and that's when you
specifically need a local context for the loop (being careful not to create
later-called functions inside the loop, risking all variables being in the
post-loop state). If you don't need a local scope for your loop, then using
$.each (or the native [].forEach in later browsers) is pointless as it only
has overhead of additional function invocations and lowering the position
in the scope chain.

When iterating over objects, however, (not arrays) then $.each is no better
than a for-in loop because (contrary to what some people think) it is not a
shortcut for for-in + if-hasOwn wrapper. When an object is passed, it
literally just does a plain for-in loop invoking the callback with the
value. jQuery does not support environments where someone extends the
native Object.prototype because it is considered harmful (an therefore
MediaWiki inherently does not support that either), so a plain for-in loop
over an object (excluding array objects) is perfectly fine according to our
conventions.

See also http://stackoverflow.com/a/1198447/319266

.... but so much for the good (and bad, evil) parts of javascript :D

-- Krinkle
_______________________________________________
Wikitech-l mailing list
Wikitech-l@lists.wikimedia.org
https://lists.wikimedia.org/mailman/listinfo/wikitech-l

Reply via email to