Open Bug 1281696 Opened 4 years ago Updated 3 years ago

iterating with let in for-loops

Categories

(Developer Documentation :: JavaScript, defect, P5)

All
Other
defect

Tracking

(Not tracked)

UNCONFIRMED

People

(Reporter: ron, Unassigned)

References

()

Details

:: Developer Documentation Request

      Request Type: New Documentation
     Gecko Version: unspecified
 Technical Contact: 

:: Details

Under "Cleaner code in inner functions" it says:

"The example above works as intended because the five instances of the (anonymous) inner function refer to five different instances of the variable i. Note that it does not work as intended if you replace let with var, since all of the inner functions would then return the same final value of i: 6. Also, we can keep the scope around the loop cleaner by moving the code that creates the new elements into the scope of each loop."

But if "i" is unique for each iteration and survives the iteration (making that inner function work), why can't i be const? This explanation mentions why "var" is useless, but not why "const" shouldn't work. I would love to see an explanation on that. Also, which block does "i" really belong to? It's not the outer block as far as I know, but it's not declared *in* the inner block either. It's sort of in limbo. Some clarification to how let inside the for-constructor works would be nice.
You can confirm it with this code:

var funcs = [],
object = {
    a: true,
    b: true,
    c: true
};

for (let key in object) {
	funcs.push(function() {
	    console.log(key);
	});
}

funcs.forEach(function(func) {
func();     // outputs "a", then "b", then "c"
});


It goes C C C
It should go A B C
You need to log in before you can comment on or make changes to this bug.