'how is closure working with let in js?
I am learning about the new features in ES6. I have a question about how let is really behaves, let's check the following example:
function aHero() {
return 'Boy'
}
function aFoil() {
return 'Rat'
}
function aDeed() {
return 'Deed'
}
let sagas = [];
let hero = aHero();
let newSaga = function () {
let foil = aFoil();
sagas.push(function () {
let deed = aDeed();
console.log(hero + deed + foil)
});
}
newSaga();
sagas[0]();
sagas[0]();
newSaga();
ES5: var scoped variable to entire function so when the code is running in browser, all variables been hoisted, on the other side in ES6 let scoped variable to its block so when run this code saga[0]() will print three words 'BoyDeedRat'
so I'm wondering how closure is really working with let ??
Solution 1:[1]
In Chrome, Safari and Firefox, let variables are local to the block, even within a loop.
Both
(function(){
let fns = [];
for (let i = 0; i < 5; i++) {
fns.push(() => { console.log(i); });
}
for (let i = 0; i < fns.length; i++) {
fns[i]();
}
})();
and
(function(){
let fns = [];
for (var i = 0; i < 5; i++) {
let num = i; // closure will refer to separate values per iteration
fns.push(() => { console.log(num); });
}
for (let i = 0; i < fns.length; i++) {
fns[i]();
}
})();
0
1
2
3
4
whereas using var instead of let in either case would print 4 five times.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | macu |
