Desugaring "for" and "let"

Axel Rauschmayer axel at rauschma.de
Mon Jul 11 14:54:32 PDT 2011


> Just recently:
> 
> https://mail.mozilla.org/pipermail/es-discuss/2011-June/015615.html (thread head)
> 
> and previously:
> 
> https://mail.mozilla.org/pipermail/es-discuss/2008-October/007826.html

Thanks!

>> Compare: With Java, you have to declare
>>   final int finalI = i;
>> inside a for loop if you want to refer to i from an inner class.
> 
> Yeah, but that sucks so let's not cite it as any kind of precedent :-|.
> 
> Anyway, for-in and for-of with let give fresh binding per iteration -- that's the plan for ES.next.
> 
> Ye olde C-style for(init; cond; update) {...} loops are thin veneer for init; while (cond) {... update}, and as Jon Z. pointed out, since you can take them apart accordingly, the binding semantics should not shift as you do.


==== Example ====

for(let i=0; i < arr.length; i++) {
    // ...
}

==== Desugars to ====

let i=0;
while(i < arr.length) {
    // ...
    i++;
}

As per "Jon’s criticism", I would expect every iteration to create a new environment whose outer environment is always the same – the environment where "i" is bound (right?). That is: "i" is stored outside the environments that are created by repeatedly "invoking" the loop body.

Furthermore, I always thought that there was an additional block wrapped around a for loop with a let, because once you leave the loop, "i" usually ceases to exist.

==== Additional block ====

{
    let i=0;
    while(i < arr.length) {
        // ...
        i++;
    }
}

One also has to consider the case where a loop is used to increment a non-local variable. That is, loops should be allowed to have side effects. I’m not sure how this applies to iterators, as they are handled by reference.

-- 
Dr. Axel Rauschmayer

axel at rauschma.de
twitter.com/rauschma

home: rauschma.de
blog: 2ality.com





More information about the es-discuss mailing list