On Sat, 2011-01-15 at 12:39 +0100, Peter van der Zee wrote:
> If all variables are declared at the top, there's no risk at all of
anyone thinking variables in the loop are bound to "a block scope of
that loop"

If you really want to make your code idiot-resistant, you still don't
have to move loop `var`s all the way to the top of function. This:

    function doSomething(things) {
        // Loop that does something
        var i, thing;
        for (i= 0; i<things.length; i++) {
            thing= things[i];
            thing.doPartOfSomething();
        }

        // Loop that does something else
        var i, thing;
        for (i= 0; i<things.length; i++) {
            thing= things[i];
            doAnotherPartOfSomething(thing);
        }
    }

is explicit and still keeps the advantage of locality for associated
declarations.

Of course for loops in particular, you can use ES5-style `Array.forEach`
and similar methods that, by taking a (potentially inline) function
argument, actually do introduce loop variables with limited scope. This
also avoids the risk of running into the Closure Loop Problem, something
that confuses even otherwise-competent programmers.

-- 
And Clover
mailto:[email protected] http://www.doxdesk.com
skype:uknrbobince gtalk:[email protected]


-- 
To view archived discussions from the original JSMentors Mailman list: 
http://www.mail-archive.com/[email protected]/

To search via a non-Google archive, visit here: 
http://www.mail-archive.com/[email protected]/

To unsubscribe from this group, send email to
[email protected]

Reply via email to