The following ES6 code's behaviour puzzled a few developers I know.
The results indicated below each snippet are run through
SpiderMonkey's implementation.

It is related to 13.6.3.2. I believe the wording of the current draft
leaves the interaction with closures open to interpretation.

    for (let i = 0; i < 3; i++);
    console.log(i)

(i is scoped, so it is not defined on line 2. So far so good.)

    for (let i = 0; i < 3; i++) {}
    console.log(i)

(same)

    let funs = [];
    for (let i = 0; i < 3; i++) funs[i] = () => console.log(i);
    funs[0]()

(shows 3, not 0: i is not captured in the closure)

    let funs = [];
    for (let i = 0; i < 3; i++) { funs[i] = () => console.log(i); }
    funs[0]()

(same)

    let funs = [];
    for (let i = 0; i < 3; i++) { let j = i; funs[i] = function() {
console.log(j); } }
    funs[0]()

(shows 0; i is captured in the closure)

According to me, it would be cleaner if the let binding in any loop
was independently captured in the closure.
_______________________________________________
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss

Reply via email to