On Sat, Jan 15, 2011 at 5:15 PM, And Clover <[email protected]> wrote:
> 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.

This is still a bad idea.

Thanks to hoisting, that second declaration doesn't do what it appears
to do (at least, not where it appears to do it), and it increases the
likelihood that a less experienced programmer (or just someone who
isn't paying close attention) will make a mistake when changing that
code later.

If another developer comes along and adds some code after the second
var statement but before the second loop that assumes that i and/or
thing are undefined, they'll be in for a surprise, because i ===
things.length and thing === things[things.length - 1].

- Ryan

-- 
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