So, trying to learn a bit about ES6, I came over this link, http://es6-features.org/#BlockScopedVariables
// ES6
let callbacks = []
for (let i = 0; i <= 2; i++) {
callbacks[i] = function () { return i * 2 }
}
callbacks[0]() === 0
callbacks[1]() === 2
callbacks[2]() === 4
// ES5
var callbacks = [];
for (var i = 0; i <= 2; i++) {
(function (i) {
callbacks[i] = function() { return i * 2; };
})(i);
}
callbacks[0]() === 0;
callbacks[1]() === 2;
callbacks[2]() === 4;
May I know why in ES5 Method we are using an immediate function to return the i*2 value?
But in ES6, just assigning the value in loop works?
Basically,
- Want to Know why this difference occurs?
- How does that loop is getting executed?
- I find the difference is due to "block scope (let) & global scope (var)", but want to know more about the execution/runtime point?
- So we don't want to use immediate function for saving the current state of variable in ES6?