Loops, Let, Closures

# Thaddee Tyl (11 years ago)

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.

# Andy Wingo (11 years ago)

On Wed 12 Feb 2014 15:22, Thaddee Tyl <thaddee.tyl at gmail.com> writes:

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

SpiderMonkey's implementation of for-let is out of date, AFAIK. I couldn't find a bug about it though.

# Brendan Eich (11 years ago)

Could you please file one?

ES6 specifies what Thaddee wants: a binding per iteration, and a "0th iteration binding" in case there's a closure capture in the first part of the head.

# Andy Wingo (11 years ago)
# Brendan Eich (11 years ago)

Thanks!

I just remembered we have a bug on for(let in) and for(let of),

bugzilla.mozilla.org/show_bug.cgi?id=449811

assigned to Jason.

I hope this is all per draft spec (and we drop the E4X-era for-each(in) if we haven't already!).

# Rick Waldron (11 years ago)

Recent relevant discussion on test262: tc39/test262#28