here's the example:
var a = [];
for (let i = 0; i < 10; i++) {
a[i] = function () {
console.log(i);
};
}
a[6](); //outputs 6
the problem is,in this case,variable declarated by let is only accessible in "for" block,so after the loops,how does the function a[6] obtain the value of i?
I translate this es6 sourse code into es5 by Bable,which output the code below:
"use strict";
var a = [];
var _loop = function _loop(i) {
a[i] = function () {
console.log(i);
};
};
for (var i = 0; i < 10; i++) {
_loop(i);
}
a[6]();
Bable create a new function _loop.So on each iteration,the i variable will be copyed and passed into the function _loop, which is a closure.And i variable is accessible after the loops.it seems like let in es6 just simplify and immitate what closure in es5 do.