Closed Bug 1281696 Opened 8 years ago Closed 4 years ago

iterating with let in for-loops

Categories

(Developer Documentation Graveyard :: JavaScript, defect, P5)

All
Other
defect

Tracking

(Not tracked)

RESOLVED WONTFIX

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
MDN Web Docs' bug reporting has now moved to GitHub. From now on, please file content bugs at https://github.com/mdn/sprints/issues/ and platform bugs at https://github.com/mdn/kuma/issues/.
Status: UNCONFIRMED → RESOLVED
Closed: 4 years ago
Resolution: --- → WONTFIX
You need to log in before you can comment on or make changes to this bug.